这个项目是用 C++ 编写的。我试图沿着一个文本文件移动,每次在屏幕上打印一个 80 个字符长的子字符串。下一步是更新 x 的起始位置,然后再次打印。我的目标是在 txt 上“滑动”。当我开始第二个流操作时,我没有收到错误,但屏幕上不再输出任何文本。 谁知道我做错了什么?在执行新操作之前是否必须关闭文件?谢谢
ifstream ifs("data.txt");
string line;
string subline;
int x=5;
while(getline(ifs,line)) {
subline=line.substr(x,80);
cout << subline;
}
system("pause");
system("cls");
x++;
//my issue!
while(getline(ifs,line)) {
subline=line.substr(x,80);
cout << subline;
}
最佳答案
是的,您确实需要在使用后关闭该文件。始终清理您在编程中所做的每一件事,尤其是文件操作。
在对文件进行实际操作之前,您应该检查文件是否确实成功打开。 当您以现有方式(使用构造函数)打开文件时,如果文件打开操作失败,您将不会返回任何内容。
您可以检查 ifstream 方法“good()”以查看流是否成功打开,或检查“fail()”以查看是否未成功打开。
例如
ifstream ifs("data.txt");
if( ifs.fail() )
{
std::cerr << "There was an error opening the file" << std::endl;
return -1; // use -1, or some sort of non-zero number representing your error code to the command line
}
// Do your reading / writing
ifs.close();
我推荐阅读 this info关于使用 ifstream 时可用的一些功能。
关于c++读取txt到字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8385839/