Yingying Zhu
Yingying Zhu

Reputation: 21

Why is my getline not reading .csv files properly?

I opened my input.csv file correctly and it has contents inside. However, when I cout what I read, they are all empty.

The input file is a questionnaire feedback with question names on the first line and corresponding points below.

An example of the input file is:

Name,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));

    }

Upvotes: 1

Views: 269

Answers (1)

AndersK
AndersK

Reputation: 36082

This line

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

is not doing what you expect it to do, you are modifying the name of the input_file so that output_file and input_file are the same. Therefore the same file is opened. Check always also the return value from getline, it is good practice.

Copy first the string to output_file, then do the insert on the output_file instead.

Upvotes: 3

Related Questions