简体   繁体   中英

Reading in a text file to an array including spaces

I have to read this text file which already exists. This code compiles and works but it only reads in one word per line.

For example: my txt file looks like this:

  • word1 word2 word3 word4
  • word5 word6 word7
  • word8 word9

But it outputs on the screen:

  • word1
  • word2
  • word3.. etc.

How can I get it to read the txt file into the array including the spaces?

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

using namespace std; 

int main()
{
    string friendConnections[9];
    string line;
    int loop = 0;

    ifstream networkFile("network.txt");

    if (networkFile.is_open())
    {
        while (!networkFile.eof())
        {
            istream& getline (networkFile >> line);
            friendConnections[loop] = line;
            cout << friendConnections[loop] << endl;
            loop++;
        }
        networkFile.close();
    }
    else cout << "Can't open file" << endl;

    return 0;
}

Use while(std::getline(networkFile,line)) instead of while(networkFile.eof()) and istream& getline (networkFile >> line);

istream operator>> goes until the whitespace which isn't what you want.

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