在c++中避免使用流的eof
Avoid using eof of istream in C++
我试图避免在我的代码中使用eof of istream,因为它应该处理文本文件,有关原因的更多信息请参阅这里。
下面的代码尝试逐行读取,但是每一步代码读取两行而不是一行。
显然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();
您不需要第二次调用getline:您已经拥有了可供使用的内容,它在line变量中。您所需要的只是将其内容取出以进行进一步标记化。这并不难做到:您只需要在line变量上调用c_str,如下所示:
char *buf = line.c_str();
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 而(!inputfile.eof())只读取第一行?
- EOF有更安全的替代方案吗?它在我的情况下不起作用
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 如何在 EOF 之前从文件中读取并将其放入字符串中?
- 如何在从文件中读取整数时使用 file.eof()?
- "eof"可以设置为流吗?
- 吃完 EOF 后重复使用 std::cin
- 文件处理,eof() 定义
- std::cin 在读取 EOF 并清除后不再读取
- 为什么 EOF 在循环扫描期间没有终止?
- cin.clear()是否保留EOF
- 而(getline(fin,str)){}即使在到达eof之后仍在处理数据
- 通过终端在文件中输入时检测EOF(文件结束)时出现问题
- 为什么如果我从键盘输入EOF克里昂不要在运行窗口打印程序的输出?
- 为什么"cin"在EOF之后不再wοrk?
- 在 <char>sizeof(int) == 1 的平台中如何编码 char_traits::eof() ?
- 读取 c++ istream 直到 EOF,同时丢弃内容
- 我的代码在捕获块中处理了正确的 eof 后到达 eof 时会引发 basic_ios::clear ?