为什么我的程序没有从文件中读取?

时间:2016-05-02 00:06:07

标签: c++ file

#include <iostream>
#include <string>
#include <fstream>

using namespace std;


int main()
{
    ifstream fin ("data1.txt");
    int ID;
    string name;
    int test1, test2, test3;

    char answer;
    cin >> answer;
    while (answer = 'Y')
    {

    fin >> ID;
    getline(fin, name);
    cout << name << endl;
    fin >> test1, test2, test3;

    cout << ID << endl;


    cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
    cin >> answer;

    }
}

http://postimg.org/image/fjknavue9/(显示错误的图片)

显示此错误。 出于某种原因,它只是读取第一个ID。然后垃圾。

This is the TXT file
211692
Ahmed, Marco
66 88 99
240885
ATamimi, Trevone
30 60 90
281393
Choudhury, Jacob 
45 55 65
272760
De la Cruz, Edward
79 89 49
199593
Edwards, Faraj
90 56 96
256109
Edwards, Bill
93 94 95
246779
Gallimore, Christian
22 88 66
270081
Lopez, Luis
100 100 100
114757
Mora, Sam
63 78 88
270079
Moses, Samuel
48 95 99
193280
Perez, Albert 
97 57 0
252830
Rivas, Jonathan
44 56 76
252830
Robinson, Albert  
85 87 89
276895
Miranda, Michael
82 72 62
280515
Robinson, Iris 
64 78 91

程序wwill只读取第一个id,但没有别的,但它会显示给出的内容,如果不是垃圾。通过了解解决方案或理解,出现了什么问题,它可以帮助我处理另一个处理相同逻辑的程序。

2 个答案:

答案 0 :(得分:0)

由于@Akshat Mahajan在你的代码中提到了两个问题,我修复并测试了它们。

还需要做一件事。您应该添加一行fin.ignore(),以便在从文件中获取整数后忽略新行。

以下是工作代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;


int main()
{
    ifstream fin ("data1.txt");
    int ID;
    string name;
    int test1, test2, test3;

    char answer;
    cin >> answer;
    while (answer == 'Y')
    {

        fin >> ID;
        fin.ignore();
        getline(fin, name);
        cout << name << endl;
        fin >> test1>> test2>> test3;

        cout << ID << endl;


        cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
        cin >> answer;

    }
}

但是,您在代码中做了一些不好的做法。不要使用answer == 'Y'作为while的条件,请尝试fin>>ID

之类的内容

答案 1 :(得分:0)

如果您选择将getline用于所有内容,则可以稍微更改一下代码。

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;


int main()
{
    ifstream fin ("data1.txt");
    int ID;
    string name, line;
    int test1, test2, test3;

    char answer;
    cin >> answer;

    while (answer == 'Y')
    {

        getline (fin, line);
        ID = stoi(line);
        getline(fin, name);
        cout << name << endl;
        getline(fin, line);
        stringstream ss(line);
        ss >> test1 >> test2 >> test3;

        cout << ID << endl;
        cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
        cin >> answer;
    }
}