繁体   English   中英

避免在C ++中使用istream的eof

[英]Avoid using eof of istream in C++

我试图避免在我的代码中使用isofream的eof,它假设处理文本文件,有关原因的更多信息,请参阅此处

下面的代码试图逐行读取,但是每一步代码都读取两行而不是一行。

显然,getline函数执行两次,并且在由strtok_s函数处理之前,数据首先被读取到buf。

如果我要忽略内部getline指令,如何将数据写入buf[]进行处理?

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();

你不需要第二次调用getline:你已经掌握了内容,它在行变量中。 您所需要的只是获取其内容以进一步标记化。 这并不难:你需要的就是在行变量上调用c_str,如下所示:

char *buf = line.c_str();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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