问题
How should I read this file if I know how many int values are after the first value but I don't know how many values are after them. My problem is when I have to read the lines that contains 2 values.
Edit: This is my file
5
27
15
42
17
35
20 1
28 2
43 3
Here is what I tried:
fin >> n;
for (i=1; i<=n; i++)
fin >> part[i];
while(!fin.eof())
{
nrT++;
fin >> tric[nrT][0];
fin >> tric[nrT][1];
}
回答1:
for (int a,b; fin >> a >> b; nrT++)
{
tric[nrT][0] = a;
tric[nrT][1] = b;
}
回答2:
Treat an end of line character the same as you would a space character, and try to parse everything that's not either of those. If you use Unicode aware regular expressions there's already a group which does this.
回答3:
Look into string streams. (I don't know the code off the top of my head). They are like cin, but you can initialize them with data from a file. Then you can use the >> operator to extract data from it and it knows how to pull out the integer value.
回答4:
First, don't use fin.eof()
. That function is only useful after a read
has failed. Something like the following should work, however:
fin >> n;
if ( !fin || n > size( part ) ) {
// Error...
}
for ( i = 0; i != n; ++ i ) {
fin >> part[i];
if ( !fin ) {
// Error...
}
}
while ( nrT < size( tric ) && fin >> tric[nrT][0] >> tric[nrT][1] ) {
++ nrT;
}
For better validation, you might want to read the file line by line, and
extract one or two elements from the line, depending on where you are in
the file. Another improvement would be to use std::vector
for the
containers, and push-back
—that way, you don't need any bounds
checking.
回答5:
Read line by line, the look for spaces in the line. If there are, use the method substring. Finally, convert the substrings obtained to integers. There are tons of examples on the internet:
substring
String to integer conversion
Hope this helps!
来源:https://stackoverflow.com/questions/8943949/c-read-from-file