Quantcast
Channel: Visual C forum
Viewing all articles
Browse latest Browse all 15302

Avoid using eof of istream in C++

$
0
0

I'm trying to avoid using eof of istream in my code which suppose to process textual files. 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();


Viewing all articles
Browse latest Browse all 15302

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>