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