从单独的文本文件中读取句子时遇到空格问题

时间:2014-10-07 05:23:01

标签: c++ string file-io

在从单独的文本文件中读取数据时,它不会保留空格,而是看起来像:

Todayyouareyouerthanyou,thatistruerthantrue

什么时候应该有空格并说:

Today you are youer than you, that is truer than true

这是我到目前为止的代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;
int main()
{
 std::ifstream inFile;
 inFile.open("Rhymes.txt", std::ios::in);
 if (inFile.is_open())
 {
     string word;
     unsigned long wordCount = 0;

     while (!inFile.eo())
     {
        cout << word;
        inFile >> word;
        if (word.length() > 0)
        {
            wordCount++;
        }
     }

     cout << "The file had " << wordCount << " word(s) in it." << endl;
 } 


 system("PAUSE");
 return 0;
}

&#34; Rhymes.txt&#34;有许多短语,如上面的那个,我只是再添加2个,所以它在这里不是很多。他们在这里:

Today you are You, that is truer than true. There is no one alive who is Youer than You.
The more that you read, the more things you will know. The more that you learn, the more places you'll go.
How did it get so late so soon? Its night before its afternoon.

任何帮助或建议将不胜感激!!我也是一个初学者,所以如果事实证明这是非常明显的事,抱歉!

3 个答案:

答案 0 :(得分:0)

让我们解决错误:inFile.eo() - &gt; inFile.eof()并包含stdlib.h for system()。现在你可以通过写cout&lt;&lt;来回放空格了。单词&lt;&lt; “”;

但是你的程序似乎已经过了1. Linux wc说了53个单词,但是你的程序说54.所以我修复了你的循环:

 while (true)
 {
    inFile >> word;
    if (inFile.eof())
      break;
    if (word.length() > 0)
    {
        wordCount++;
        cout << word << " ";
    }
 }

现在它同意wc。

答案 1 :(得分:0)

如何将空格插回到输出中,而不是这个

cout << word;

你说这个:

cout << word << " ";

另一种选择是从输入文件中读取整行,然后将它们拆分为单词。

答案 2 :(得分:0)

我看到的问题:

  1. 您在第一次阅读之前写出word

  2. 使用inFile >> word阅读单词会跳过空格。您需要添加代码来写入空格。

  3. 我不确定您在使用以下代码块时的想法。但是,没有必要。

    if (word.length() > 0)
    {
        wordCount++;
    }
    
  4. 您可以将while循环简化为:

     while (inFile >> word)
     {
        cout << word << " ";
        wordCount++;
     }
    

    这将在末尾打印一个额外的空白区域。如果这是令人反感的,您可以添加更多逻辑来解决这个问题。

相关问题