我的代码出了什么问题?我想从文件中获取intput(第一个字符串,然后是char,然后是int)。我想要整个文件。这是我的代码。这让我很痛苦。我能做什么?请帮帮我。
//file handling
//input from text file
//xplosive
#include<iostream>
#include<fstream>
using namespace std;
ifstream infile ("indata.txt");
int main()
{
const int l=50;
//string t_ques;
char t_ques[l];
char t_ans;
int t_time_limit;
while(!infile.eof())
//while(infile)
{
infile.getline(t_ques,l);
//infile >> t_ans ;
infile.get(t_ans);
infile >> t_time_limit;
cout << t_ques << endl;
cout << t_ans << endl;
cout << t_time_limit << endl;
}
return 0;
}
我的indata.txt文件包含
what is my name q1?
t
5
what is my name q2?
f
3
what is my name q3?
t
4
what is my name q4?
f
8
out put should be the same.
but my while loop don't terminate.
答案 0 :(得分:3)
许多事情:
read
,因为它不会跳过空白#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream infile ("indata.txt");
std::string t_ques;
char t_ans;
int t_time_limit;
std::getline(infile, t_ques);
while (infile >> t_ans >> t_time_limit)
{
cout << t_ques << endl;
cout << t_ans << endl;
cout << t_time_limit << endl;
infile.ignore();
std::getline(infile, t_ques);
}
}
答案 1 :(得分:0)
尝试使用此表达式:
infile.open("indata.txt", ios::in);
// ...same loop...
infile >> t_ques >> t_ans >> t_time_limit;
// At the end close the file
infile.close();