所以我试图从文本文件中读取。它表明我可以成功读取文件但是当我尝试cout值时,它只显示0,而我在文本文件中有其他值。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
std::ifstream file("numbers.txt");
if (file) {
cout << "Managed to read file successfully. \n";
}else{
cout << "Unable to read file.";
}
int x, y;
file >> x >> y;
cout << "Num 1: " << x << endl;
cout << "Num 2: " << y << endl;
return 0;
}
答案 0 :(得分:0)
上面的代码将打印您的操作状态,如果您想要阅读和显示内容,您必须编写代码,如下所示:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream stream1("D:\\file1.txt");
char a[80];
if(!stream1)
{
cout << "While opening a file an error is encountered" << endl;
}
else
{
cout << "File is successfully opened" << endl;
}
while(!stream1.eof())
{
stream1 >> a;
cout << a << endl;
}
return(0);
}
答案 1 :(得分:0)
使用numbers.txt文件
45
15
您的代码工作使用gcc查找。
int main()
{
std::ifstream file("numbers.txt");
if (file)
{
cout << "Managed to read file successfully. \n";
int x, y;
file >> x >> y;
cout << "Num 1: " << x << endl;
cout << "Num 2: " << y << endl;
}
else
{
cout << "Unable to read file.";
}
return 0;
}