简体   繁体   中英

Avoid using eof of istream in C++

I'm trying to avoid using eof of istream in my code which suppose to process textual files, for more information about the reason see here .

The following code trying to read line by line, however with each step the code read two lines instead of one.

Apparently getline function is executed twice, and the data is read to the buf first before being processed by strtok_s function.

If I'm going to ignore the internal getline instruction how can I write data into buf[] to be processed?

while (getline(fin, line))
//while(!fin.eof())
 {
    // read an entire line into memory
    char buf[MAX_CHARS_PER_LINE];
    fin.getline(buf, MAX_CHARS_PER_LINE);

    // parse the line into blank-delimited tokens
    int n = 0; // a for-loop index
    int s = 0;
    // array to store memory addresses of the tokens in buf
    const char* token[MAX_TOKENS_PER_LINE] = {}; // initialize to 0
    char *next_token;
    // parse the line
    token[0] = strtok_s(buf, DELIMITER, &next_token); // first token
    if (token[0]) // zero if line is blank
    {
        for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
        {
            token[n] = strtok_s(0, DELIMITER, &next_token); 

            if (!token[n]) break; // no more tokens
        }
    }

    // process (print) the tokens
    for (int i = 0; i < n; i++) // n = #of tokens
        cout << "Token[" << i << "] = " << token[i] << endl;
    cout << endl;
}

fin.clear();
fin.close();

You do not need a second call of getline: you have the content at your disposal already, it's inside the line variable. All you need is getting its content out for further tokenization. That's not difficult to do: all you need is to call c_str on the line variable, like this:

char *buf = line.c_str();

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