为什么我的getline无法正确读取.csv文件?

时间:2019-07-03 04:17:09

标签: c++

我正确打开了input.csv文件,其中包含内容。 但是,当我cout阅读的内容全部为空时。

输入文件是问卷反馈,第一行带有问题名称,下面是相应的点。

输入文件的示例是:

名称,Q1,Q2

Ann,7,6

Ben,5,6

int main(){
    string input_file;
    string output_file;
    cout<<"input file name"<<endl;
    cin>>input_file;
    output_file = input_file.insert(input_file.length()-4, "_out");

    ifstream fin(input_file);
    if(fin.is_open()){
        cout<<"the file name is correct. ";
    }
    else{
        cout<<"the file name does not exist.";
        return 0;
    }
    ofstream fout(output_file);
    int sample_size = 0;
    int highest_point = 0;

    cout<<"What is the highest point possible?"<<endl;
    cin>>highest_point;

    vector<Tag*> tags;
    string first_line;
    string tag_name;
    getline(fin, first_line);
    //as reminded, I added a check here;
    if (!std::getline(fin, first_line)) { std::cerr << "Failed to read first line\n"; std::exit(1); }
    //this does prints out the error message so I guess the getline function is not even working correctly.

    //When I cout first_line here, it prints nothing on my terminal
    cout<<first_line;
    istringstream stringIn1(first_line);
    while(getline(stringIn1, tag_name, ',')){
        //WHEN I COUT tag_name HERE, IT PRINTS NOTHING ON MY TERMINAL EITHER
        cout<<tag_name;
        tags.push_back(new Tag(tag_name));

    }

1 个答案:

答案 0 :(得分:3)

此行

output_file = input_file.insert(input_file.length()-4, "_out");

没有按照您的期望做,您正在修改input_file的名称,以便output_file和input_file相同。因此,将打开相同的文件。还要经常检查getline的返回值,这是一个好习惯。

首先将字符串复制到output_file,然后在output_file上进行插入。