[英]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.