[英]Error in reading from a .txt file in c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
//reading the text file
ifstream inputFile("testfile1.txt");
inputFile.open("testfile1.txt");
while(!inputFile.eof())
//eof till end of file, reads the txt till end of file
{
string str;
getline(inputFile,str);
cout <<str<< endl;
}
inputFile.close();
return 0;
}
//我遇到的问题是它无法读取文件或其中的任何内容。 不执行任何操作,表明程序以退出代码结尾:0。有人可以检查代码中的错误吗?
第一个错误:您两次打开输入文件。 根据C ++标准,关于第二个打开请求(直接调用open
成员)的行为:
C ++ 11§27.9.1.9 [ifstream.members / 3]
void open(const char* s, ios_base::openmode mode = ios_base::in);
效果:调用
rdbuf()->open(s, mode | ios_base::in)
。 如果该函数未返回空指针,则调用clear(), 否则调用setstate(failbit) (这可能会引发ios_base :: failure(27.5.5.4))。
因此,它会问一个问题, rdbuf()->open(...)
做什么? 好吧, std::ifstream
使用filebuf
进行缓冲,并再次按照标准:
C ++ 11§27.9.1.4[filebuf.members / 2]
basic_filebuf<charT,traits>* open(const char* s, ios_base::openmode mode);
效果: 如果
is_open()
!= false,则返回空指针 。 否则,根据需要初始化filebuf。 ...
简而言之,双重打开会使流进入失败状态,这意味着从那时起,所有与数据相关的操作都将彻底失败。
第二个错误:在循环条件表达式中不正确使用.eof。 修复第一个错误后,您将遇到此问题。 在以下问题中,解释不正确的原因远比我在这里可以解释的要好。
为什么在循环条件内的iostream :: eof被认为是错误的?
只需说一下,检查您的IO操作,而不仅仅是检查流的eof状态即可。 养成这个习惯并坚持下去。
同时解决这两个问题,您的代码实际上可以简化为:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream inputFile("testfile1.txt");
std::string str;
while (std::getline(inputFile, str))
std::cout << str << std::endl;
}
显然,如果您要编写更可靠的代码,则可能要在其中执行一些错误处理,例如:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main()
{
std::ifstream inputFile("testfile1.txt");
if (!inputFile)
{
std::cerr << "Failed to open file\n";
return EXIT_FAILURE;
}
std::string str;
while (std::getline(inputFile, str))
std::cout << str << std::endl;
}
根据本文,这是读取文件的正确方法! 代码中的问题似乎是您使用的是IDE,它找不到您要给ifstream的路径,因此请尝试提供文件的完整路径。 希望它能对你有所帮助。
string line;
ifstream f("/YOUPARTH/testfile1.txt");
if (!f.is_open())
perror("error while opening file");
while(getline(f, line)) {
cout << line << endl;
}
if (f.bad())
perror("error while reading file");
return 0;
翻译while语句:“而inputFile在文件末尾” ..您想要否定它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.