[英]C++ using ifstream to read file
我有一些關於在 C++ 中使用std::ifstream
問題。
大多數是我找不到答案的一般問題,因此對其他人也可能有用。
無論如何,我使用#include <fstream>
並制作了一個變量char line[20]
。
有一個文本文件,其中包含幾行模式jxxx
(其中x
是數字),如下所示:
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();
所以擔心的是:
為什么在getline
方法中需要數字?
line
末尾是否自動有\\0
? 因為當我們創建像char text[5]; text = "abc1"
這樣的char
變量時char text[5]; text = "abc1"
char text[5]; text = "abc1"
,它實際上被保存為"acd1\\0"
並且在每個jxxx
行之后的文件 ( \\n
) 中的jxxx
行會發生什么? (我想在比這更復雜的代碼中使用這些行,所以想知道)
程序會自動移動到下一行嗎? 如果沒有,我如何告訴它轉到下一行?
您正在調用std::ifstream::getline()
,它采用指向緩沖區的char*
指針進行輸出。 getline()
要求您指定該緩沖區的最大大小,以便它不會溢出。 如果您想處理可變長度的行而不用擔心溢出,您應該將line
更改為std::string
並使用std::getline()
代替。
如果成功, std::ifstream::getline()
將空終止輸出緩沖區。 這意味着最多, getline()
讀取的值將比請求的最getline()
1,因此請確保在傳入的大小中為空終止符留出空間(如果遇到換行符或 EOF, getline()
讀取的值可能會更少)。 至於換行符本身,它們被getline()
吞掉,它們不會出現在緩沖區中。
是的,代碼會自動移動到下一行,所以你可以在循環中繼續調用getline()
。
旁注:
while (!rfile.eof())
不好用。 使用while (rfile)
代替。 或者更好, while (rfile.getline(line, 20))
。 無論哪種方式都會解決open()
和getline()
中發生的任何錯誤,但后者確保在getline()
失敗時不會調用cout
。
cout >> data >> endl;
也是錯的。 您需要將<<
與std::cout
一起使用,而data
應改為line
。
試試這個:
#include <iostream>
#include <fstream>
char line[20];
std::ifstream rfile;
rfile.open("path-to-txt-file");
if (rfile.is_open()) {
while (rfile.getline(line, 20)) {
std::cout << line << std::endl;
}
rfile.close();
}
或這個:
#include <iostream>
#include <fstream>
#include <string>
std::string line;
std::ifstream rfile;
rfile.open("path-to-txt-file");
if (rfile.is_open()) {
while (std::getline(rfile, line)) {
std::cout << line << std::endl;
}
rfile.close();
}
聽起來你想要像 getline(stream, &string, delemter ) 一樣使用的 getline 函數,所以在你的情況下
std::string buff;
getline( rfile, buff )
這將讀取文件直到找到換行符並將字符串(減去換行符)存儲在 buff 中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.