因此用户将输入一个包含任何文本的文件,程序需要通读每个字符并计算每个字符的数量(仅限大写和小写字母)。所以,可能有 50 个 A,23 个 B,等等......
这是我目前在 main.cc 中的内容:
char character;
int i = 65; //this is the iterator to go through upper and lowercase letters
int count = 0; //counts number of characters and resets when exiting the loop and after using cout
ifstream file(filename); //filename is a string the user inputs
while (i != 0) {
while (file >> character) {
int a = character;
cout << a << endl; //testing: outputs the correct number for the letter
if (i == a) { //but for some reason this part isn't working?
count++;
}
}
cout << count << endl; //this outputs 0 every time
count = 0;
i++;
if (i == 91) i = 97; //switch to lower case
if (i == 123) i = 0; //exit loop
}
非常感谢您的帮助!谢谢:)
最佳答案
让我们假设文本是 ASCII 或扩展 ASCII 格式,这样最多有 256 个可能的字符。
您可以使用数组来保存给定字符的出现次数。每个插槽对应一个字符;相反,字符可以用作数组的索引。
示例:
unsigned int MAXIMUM_CHAR_VALUES = 256U;
unsigned int occurrences[MAXIMUM_CHAR_VALUES] = {0};
char c;
while (my_text_file >> c)
{
++occurrences[c];
}
// Print them out
for (unsigned int i = 0; i < MAXIMUM_CHAR_VALUES; ++i)
{
if (!isprint(i))
{
cout << "0x" << hex << i;
}
else
{
c = static_cast<char>(i);
cout << c;
}
cout << ": " << occurrences[i] << "\n";
}
如果您必须使用“节点”,您可以将数组更改为节点数组。
还有其他结构可以使用,例如二叉树。
关于c++ - 通读文件中的字符并计算有多少个字母 [c++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29974332/