0

我试图避免在我的代码中使用 istream 的 eof 来处理文本文件,有关原因的更多信息,请参见此处

以下代码尝试逐行读取,但是每一步代码读取两行而不是一行。

显然getline函数执行了两次,数据先读到buf,然后再被strtok_s函数处理。

如果我要忽略内部 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();
4

1 回答 1

2

您不需要第二次调用 getline:您已经拥有了可以使用的内容,它位于 line 变量中。您所需要的只是获取其内容以进行进一步的标记化。这并不难做到:您只需要在 line 变量上调用 c_str,如下所示:

char *buf = line.c_str();
于 2013-06-01T14:08:20.630 回答