c++ - 我不明白如何在 .txt 文件字符串输入中使用 toupper 和 isalpha
问题描述
我的程序在很大程度上是不完整的,但我认为使用 toupper 修改从文本文件输入的字符串可以将所述字符串的所有字符更改为大写。我读到它适用于 int 类型,或者在这种情况下我认为是 Ascii。但我不确定从这里去哪里。就初学者 C++ 而言,从文本文件转换和检查字符串的最有效方法是什么?
我搜索了这个问题并找到了多种方法,例如使用 std::transform,但我觉得我的导师只希望我们使用 Tony Gaddis 的《从 C++ 开始》一书中教授的方法。不幸的是,我没有在我的书中找到任何关于 toupper 用于文本文件输入的参考,仅用于 char 值。为了教育起见,我希望你知道我应该在这里使用什么以及为什么。欢迎推荐阅读。
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string text;
ifstream textFile;
int ch;
textFile.open("letter_count.txt", ios::in);
toupper(textFile.get());
isalpha(textFile.get());
if (textFile)
{
// Read an item from the file.
getline(textFile, text);
// While the last read operation
// was successful, continue.
while (textFile)
{
if (textFile)
// Display the last item read.
cout << text << endl;
// Read the next item.
getline(textFile, text);
}
// Close the file.
textFile.close();
}
else
{
cout << "ERROR: Cannot open file. \n";
}
cout << "The most common letter is " " with " " occurances. \n";
cout << "The least common letter is " " with " " occurances. \n";
system("pause");
}
使用 toupper 没有任何结果。
解决方案
那是因为 toupper 只取一个 int 值。注意这里: http ://www.cplusplus.com/reference/cctype/toupper/?kw=toupper
您必须遍历字符串中的每个字符才能进行转换。
推荐阅读
- javascript - 如何在带有后备的 JavaScript 中设置 CSS 样式属性?
- r - 比较2个不同大小的数据框
- python - Groupby 和列表类别
- android - Flutter InAppWebView 如何禁用跨域策略?
- ansible - 执行“/tmp/terraform_1843617083.sh”时出错:进程以状态 100 退出
- python-3.x - 嵌套循环的更有效方法
- soap - SOAP 服务调用的 Junit
- mysql - 通过每个时间戳在查询中迭代计算
- nginx - 使用 Nginx 中的代理无法加载 Css 文件
- java - Java < 15 和 >= 15 的不同 Nashorn 引擎?