如何在C++中从一个文件中读取字符串、字符和整数,直到找到文件末尾(eof)?

3
我的代码有什么问题?我想从文件中获取输入(首先是一个字符串,然后是一个字符,最后是一个整数)。我希望这个过程可以针对整个文件。以下是我的代码。这使我很痛苦。我该怎么办?请帮帮我。
//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.

3
你提供什么输入?你得到什么输出? - simonc
2
可以提供一些示例输入,即输入文件的示例内容。 - Shamim Hafiz - MSFT
1
我的名字是什么 q1? t 5 我的名字是什么 q2? f 3 我的名字是什么 q3? t 4 我的名字是什么 q4? f 8 - Xplosive
@Xplosive,如果您编辑问题而不是将其作为评论发布,那么理解文件内容和输出结果会更容易。 - simonc
2个回答

3

以下是需要注意的几点:

  • EOF检查并不总是合适的。相反,应该检查流的状态。
  • 不要使用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);
    }
}

您可以在Coliru上实时查看:点击此处


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();

不会解析整个问题。 - sehe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接