【问题标题】:Having trouble with spaces while reading in sentences from separate text file从单独的文本文件中读取句子时出现空格问题
【发布时间】:2014-10-07 05:23:00
【问题描述】:

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

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;
}

“Rhymes.txt”有很多短语,例如上面的一个,我只添加 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.

任何帮助或建议将不胜感激!另外我是初学者,所以如果这真的很明显,对不起!

【问题讨论】:

    标签: c++ string file-io


    【解决方案1】:

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

    cout << word;
    

    你这样说的:

    cout << word << " ";
    

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

    【讨论】:

      【解决方案2】:

      我看到的问题:

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

      2. 使用inFile &gt;&gt; word 读取单词会跳过空格。您需要添加代码来编写空格。

      3. 我不确定您对以下代码块的想法。但是,没必要。

        if (word.length() > 0)
        {
            wordCount++;
        }
        

      您可以将while 循环简化为:

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

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

      【讨论】:

        【解决方案3】:

        让我们改正错字:inFile.eo() -> inFile.eof() 并为 system() 包含 stdlib.h。现在您可以通过编写 cout 来放回空格

        但是您的程序似乎比 1.Linux wc 说 53 个单词,但您的程序说 54 个单词。所以我这样修复了您的循环:

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

        现在它与 wc 一致。

        【讨论】:

          猜你喜欢
          • 2021-09-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多