简体   繁体   中英

Having trouble with spaces while reading in sentences from separate text file

While reading in data from a separate text file, it doesn't keep the spaces and instead looks comes out looking like :

Todayyouareyouerthanyou,thatistruerthantrue

When it should have the spaces and say:

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

Here is my code that I have so far:

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

The "Rhymes.txt" has many phrases such as the one above and I'll just add 2 more so it's not a lot on here. Here they are:

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.

Any help or advice would be greatly appreciated!! Also I am a beginner so if this turns out to be something really obvious, sorry!

Let's fix the typo: inFile.eo() -> inFile.eof() and include stdlib.h for system(). Now you can put the spaces back by writing cout << word << " ";

But your program seems to be out by 1. Linux wc says 53 words but your program says 54. So I fixed your loop like this:

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

Now it agrees with wc.

How about inserting the spaces back to your output, so instead of this

cout << word;

You put this:

cout << word << " ";

Another option would be to read whole lines from your input file and then split them to words.

Issues that I see:

  1. You are writing out word before the first read.

  2. Reading the words using inFile >> word skips the white spaces. You need to add code to write the white spaces.

  3. I am not sure what you were thinking with the following block of code. But, it is not necessary.

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

You can simplify your while loop to:

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

This will print an extra white space at the end. If that is objectionable, you can add more logic to fix that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM