简体   繁体   中英

c++ parsing lines in file as streams

I want to parse a file which describes a set of data line by line. Each datum consists of 3 or four parameters: int int float (optional) string.

I opened file as ifstream inFile and used it in a while loop

while (inFile) {

    string line;
    getline(inFile,line);
    istringstream iss(line);


    char strInput[256];

    iss >> strInput;
    int i = atoi(strInput);

    iss >> strInput;
    int j = atoi(strInput);

    iss >> strInput;
    float k = atoi(strInput);

    iss >> strInput;

    cout << i << j << k << strInput << endl;*/


}

The problem is that the last parameter is optional, so I'll probably run into errors when it is not present. How can i check in advance how many parameters are given for each datum?

Furthermore,

    string line;
    getline(inFile,line);
    istringstream iss(line);

seems a bit reduldant, how could I simplyfiy it?

Use the idiomatic approach in this situation, and it becomes much simpler:

for (std::string line; getline(inFile, line); ) {
    std::istringstream iss(line);
    int i;
    int j;
    float k;

    if (!(iss >> i >> j)) {
        //Failed to extract the required elements
        //This is an error
    }

    if (!(iss >> k)) {
        //Failed to extract the optional element
        //This is not an error -- you just don't have a third parameter
    }
}

By the way, atoi has some highly undesired ambiguity unless 0 is not a possible value for the string you're parsing. Since atoi returns 0 when it errors, you cannot know if a return value of 0 is a successful parsing of a string with a value of 0 , or if it's an error unless you do some rather laborious checking on the original string you had it parse.

Try to stick with streams, but in situations where you do need to fall back to atoi type functionality, go with the strtoX family of functions ( strtoi , strtol , strtof , etc). Or, better yet, if you're using C++11, use the stoX family of functions.

You could use a string tokenizer How do I tokenize a string in C++?
In particular: https://stackoverflow.com/a/55680/2436175

Side note: you do not need to use atoi, you could simply do:

int i,j;
iss >> i >> j;

(but this wouldn't handle alone the problem of optional elements)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM