C++ read from file

前提是你 提交于 2020-01-16 20:57:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!