[英]How can I read strings from a .txt file in a loop in C++
我的代碼:
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string index[8];
int main() {
int count = 0;
ifstream input;
//input.open("passData.txt");
while (true) {
input.open("passData.txt");
if (!input) {
cout << "ERROR" << endl;
system("pause");
exit(-1);
}
else {
if (input.is_open()) {
while (!input.eof()) {
input >> index[count];
count++;
}
}
for (int i = 0; i < 8; i++) {
cout << index[i] << endl;
}
}
input.close();
}
return 0;
}
我的方法:從頭開始打開文件,然后在讀取行時立即將其關閉。 同樣,每一行都應該是數組中的單個條目。
但是,在迭代器中名為“ xutility”的文件中出現錯誤。 輸出為“ passData.txt”文件,僅讀取一次,然后顯示錯誤。
因此,我的問題是:如何循環讀取數組條目中文件的每一行?
謝謝!
我在這段代碼中看到的問題是,您不會像以往一樣打破無限循環。 因此,您將繼續增加count
,最終超出了您的名為index
的字符串數組的范圍。
看下面的代碼,我認為它可以完成您的任務,但是更簡單:
string strBuff[8];
int count = 0;
fstream f("c:\\file.txt", ios::in);
if (!f.is_open()) {
cout << "The file cannot be read" << endl;
exit(-1);
}
while (getline(f, strBuff[count])) {
count++;
}
cout << strBuff[3] << endl;
從流中提取時,應檢查結果,而不是事先進行測試。
您不需要調用open
,接受字符串的構造函數就可以做到這一點。 您不需要調用close
,析構函數會這樣做。
您只應輸出已閱讀的行。
請注意,您應該停止兩個 ,如果你的文件用完線,或者如果您已經閱讀8線
您可以丟棄大部分已編寫的內容。
#include <iostream>
#include <fstream>
#include <string>
int main()
{
string index[8];
std::size_t count = 0;
for(std::ifstream input("passData.txt"); (count < 8) && std::getline(input, index[count]); ++count)
{
// this space intentionally blank
}
for(std::size_t i = 0; i < count; ++i)
{
std::cout << index[i] << std::endl;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.