问题
I have a text file which has some number of integers in each line. Example:
1 2 4
3
0 4
2 3
Here 1st line means that the 1st node is connected to nodes numbered 1, 2 and 5. Blank line means 4th node isn't connected to any node.
This gives me a directed graph. This SO question might have been helpful but it assumes each line to have 2 integers, whereas in this case it can have any number of integers from 0 to N-1(N is no. of nodes).
I just want to know how to read this text file. If I had two integers per line, I could have done infile >> a >> b. How to know that "\n" or end of line has occured. I am not asking for code that makes directed graph.
回答1:
The accepted answer from the linked question already shows you how to read line by line, which you need to do for your code and the first part shows a loop how to read all numbers from your line (istringstream). Because you don't have a fixed number of entries, you might want to store them in a std::vector.
回答2:
I do not think that this is homework, since the acutal topic are digraphs.
Therefore some code. But, you have to do the error handling yourself.
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
typedef std::vector<int> nl_t;
typedef std::vector<nl_t> nll_t;
int main()
{
std::ifstream is("test.dat");
std::string str;
nll_t nll;
while(std::getline(is,str)) {
std::istringstream ss(str);
nl_t nl;
int i;
while(ss >> i) {
nl.push_back(i);
}
nll.push_back(nl);
}
}
/**
Local Variables:
compile-command: "g++ -g test.cc -o test.exe; ./test.exe"
End:
*/
回答3:
Follow this Link http://www.c-plusplus.de/forum/p1940874#1940874. It is enough to read the code. It is not necessary to understand the german text.
In Your case You have to change in Line 18 of the main-programm from while( datei >> ws )
to while( datei )
and delete the lines 23 and 24. Because in Your case an empty line is an information.
Or Your main can look like this:
ifstream file("input.txt");
if( !file.is_open() )
{
cerr << ">Error by opening the file\n";
return -2;
}
for( int node1 = 1; file.good(); ++node1 )
{
for( int node2; !is_endl(file) && file >> node2; )
cout << "Node " << node1 << " is connected with " << node2 << endl;
}
来源:https://stackoverflow.com/questions/22562221/read-adjacency-list-of-digraph-from-a-text-file-in-c