【发布时间】:2015-04-30 17:38:08
【问题描述】:
所以用户将输入一个包含任何文本的文件,程序需要通读每个字符并计算每个字符的数量(仅限大写和小写字母)。所以,可能有 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
}
感谢您的帮助!谢谢:)
【问题讨论】:
-
我认为 file>> 字符给出了单词而不是字符。因此,当您执行 int a = character 时,您实际上错过了其余字符。
-
@InQusitive:
character是char类型,所以file >> character只会读取单个字符,而不是整个单词。 -
问题atm是,您在寻找第一个字符('A')时将文件读到最后,然后文件流已达到EOF!所以不会有任何数据留在流中。我也会在 (!file.eof())
-
@Andy:或者只是一个数组
-
尼德霍格,你说得对。它只经过一次内部循环并且不会返回。现在想出一种不同的方法来做到这一点......