我有一些關於在C++中使用std::ifstream
的問題。使用ifstream來讀取文件的C++
大部分是一般性問題,我無法找到答案,所以也可能對其他人有用。
無論如何,我使用#include <fstream>
並作出變量char line[20]
。
有具有圖案jxxx
(其中x
s爲數字)的幾行的文本文件,如:
j1234 j5678 j1111 (and so on)
所以,我這樣做:
#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();
所以關注的是:
爲什麼在需要的數字方法?
確實
line
有沒有\0
最後自動?因爲當我們創建char
變量像char text[5]; text = "abc1"
這樣的變量時,它實際上被保存爲"acd1\0"
,並且在每個jxxx
行之後的文件末尾(\n
)會發生什麼? (我想用比這更復雜的代碼行,所以想知道)程序會自動移動到下一行嗎?如果不是,我該如何告訴它去下一行?
'這裏爲什麼需要20個?',因爲不是使用C++字符串(std :: string),而是使用c字符串。 – drescherjm
'while(!rfile.eof()){'https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – drescherjm