我对在 C++ 中使用 std::ifstream
有一些疑问。
大多数是我找不到答案的一般问题,因此对其他人也可能有用。
无论如何,我使用 #include <fstream>
并创建了一个变量 char line[20]
。
有一个文本文件包含多行模式 jxxx
(其中 x
是数字),如下所示:
j1234
j5678
j1111
(等等)
所以,我这样做:
#include <iostream>
#include <fstream>
char line[20]
ifstream rfile;
rfile.open("path-to-txt-file");
while (!rfile.eof()) {
rfile.getline(line, 20); (why is 20 needed here?)
cout >> data >> endl;
}
rfile.close();
所以担心的是:
为什么
getline
方法中需要数字?line
是否自动在末尾有\0
? because when we createchar
vars likechar text[5]; text = "abc1"
, it is actually saved as"acd1\0"
and what happens to the endlines in the file (\n
) 在每个jxxx
行之后? (我想在比这更复杂的代码中使用这些行,所以想知道)程序会自动移动到下一行吗?如果没有,我如何告诉它转到下一行?
原文由 Atem 发布,翻译遵循 CC BY-SA 4.0 许可协议
请参阅 将数组传递给 C++ 中的函数