【发布时间】:2018-04-25 12:18:47
【问题描述】:
这里是 C++ 初学者和编程
我想编写一个程序来计算文件中的字数。 我只用一个文件对其进行测试,但它应该适用于具有不同格式的其他文件,即。多个空格。 (我假设现在文件打开等没有问题)
这是我的代码:
#include <iostream> // these are the only imports I can use
#include <fstream>
#include <string>
using namespace std;
ifstream fin("story.txt"); // open the file called filename
void skip_space(char c) {
cout << "skip_space()\n";
while (c == ' ' || c == '\n' || c == '\t') { // as long as char is space
c = fin.get(); // get next character from file
if (fin.eof()) { // if eof is raised
return;
}
} // while
return;
}
void skip_char(char c) {
cout << "skip_char()\n";
while (c != ' ' || c != '\n' || c != '\t') { // as long as char is not space
c = fin.get(); // get next character from file
if (fin.eof()) { // if eof is raised
return;
}
}
return;
}
void num_words() {
cout << "num_words()\n";
int word_count = 0;
char c = fin.get(); // get first character of file
while (!fin.eof()) { // while not end of file
if (c == ' ' || c == '\n' || c == '\t') {
skip_space(c); // loops until an nonblank character is reached
} else { // if not a blank
word_count++; // increment count
skip_char(c); // loops until a space is reached
}
}
cout << "story.txt" << " has " << word_count << " words\n";
// prints a message to cout indicating the number of words in filename.
// A word is defined as the string that an input stream (such as cin) returns when reading a string value.
}
int main() {
num_words();
}
这是文件的内容:
One day
a green
a frog ate a
princess.
当我运行代码时,输出是
num_words()
skip_char()
story.txt has 1 words
问题是 word_count 是 1 而不是 9。总的来说我很困惑。任何帮助将不胜感激!
【问题讨论】:
-
(c != ' ' || c != '\n' || c != '\t')应该是(c != ' ' && c != '\n' && c != '\t') -
三不是四。四不是三。每隔一个数字既不是三也不是四。因此,每个数字都不是三或四。
-
哦,我怎么没看到,谢谢!
标签: c++ while-loop eof word-count