Reputation: 117
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:
But it outputs on the screen:
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;
}
Upvotes: 2
Views: 3724
Reputation: 21317
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.
Upvotes: 1