【问题标题】:Count words program reading whole file as one word计算单词程序将整个文件读取为一个单词
【发布时间】: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 != ' ' &amp;&amp; c != '\n' &amp;&amp; c != '\t')
  • 三不是四。四不是三。每隔一个数字既不是三也不是四。因此,每个数字都不是三或四。
  • 哦,我怎么没看到,谢谢!

标签: c++ while-loop eof word-count


【解决方案1】:

如果你写while (c != ' ' || c != '\n' || c != '\t'),那么无论c的值是多少,这个条件总是会满足(因为对于任何c,它肯定要么不同于' ',要么不同于'\n' )。

你的意思可能是while (! (c==' ' || c !== '\n' || c == '\t')) { ...

进一步注意,当您使用 C++ 标记问题时,您可以使用 cin &gt;&gt; aString,它会自动跳过任何空格,并简单地计算此操作成功的频率。

【讨论】:

  • 伙计,我让它变得比它需要的复杂得多。非常感谢您的回答!
【解决方案2】:

您的程序中有一个小的逻辑流程。问题出在您的 skip_char 函数中。 看这一行:

while (c != ' ' || c != '\n' || c != '\t')

想想如果你读取空格字符会发生什么。条件应该是:

 while (c != ' ' && c != '\n' && c != '\t')

我强烈建议您了解您的情况为何出错,并学习如何自己查找此类错误,例如考虑您可以为代码添加什么样的打印以找到此错误。另一种选择是尝试熟悉在您工作的系统中工作的调试器。

【讨论】:

  • 谢谢!我将从现在开始使用:)
猜你喜欢
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多