Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

Not sure why I am getting C++ error with cin and getline

I am trying to go through a CSV file that is formatted like this:

4305,2.7,59338,"Autauga County, AL"
14064,2.7,57588,"Baldwin County, AL"

Here is an adapted version of the code:

using namespace std;
 int main(){
    string newl;
    //getline(cin, newl);

 while(getline(cin,newl,',')){

    double cases1 = stod(newl);
    //cin.ignore();
    cout << cases1 << ' ';
    cout << "numbaone" << endl;

    getline(cin,newl,',');
    //cin.ignore();
    double unemploymentrate1 = stod(newl);
    cout << unemploymentrate1 << ' ';
    cout << "numbatwo" << endl;


    getline(cin,newl,',');
    double income1 = stod(newl);
    cout << income1 << ' ';
    cout << "numbathree"  << endl;

    cin.ignore();
    getline(cin,newl);
    }
 }

When I just input one line it gives me the correct output which for 1882,3.1,46064,"Bibb County, AL" is

1882 numbaone   
3.1 numbatwo    
46064 numbathree

However, when I copy and paste multiple lines as input such as

1530,3.8,34382,"Barbour County, AL"
1882,3.1,46064,"Bibb County, AL"

the output gets really messed up:

1530,3.8,34382,"Barbour County, AL"
1882,31530 numbaone
3.8 numbatwo
34382 numbathree
.1,46064,"Bibb County, AL"
1882 numbaone
3.1 numbatwo
46064 numbathree

any help would be very much appreciated.

question from:https://stackoverflow.com/questions/65599605/not-sure-why-i-am-getting-c-error-with-cin-and-getline

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to define an string stream to parse data for each line .

#include <iostream>
#include <sstream>

using namespace std;

int main() {

    string newl;

    while (getline(cin, newl)) {

        stringstream stream(newl);

        getline(stream, newl, ',');
        double cases1 = stod(newl);
        cout << cases1 << ' ';
        cout << "numbaone" << endl;

        getline(stream, newl, ',');
        double unemploymentrate1 = stod(newl);
        cout << unemploymentrate1 << ' ';
        cout << "numbatwo" << endl;

        getline(stream, newl, ',');
        double income1 = stod(newl);
        cout << income1 << ' ';
        cout << "numbathree" << endl;
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...