简体   繁体   English

不知道为什么我在 cin 和 getline 中出现 C++ 错误

[英]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:我正在尝试通过格式如下的 CSV 文件 go :

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当我只输入一行时,它给了我正确的 output 对于1882,3.1,46064,"Bibb County, AL " 是

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: output 真的搞砸了:

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.任何帮助将不胜感激。

You need to define an string stream to parse data for each line.您需要定义一个字符串 stream 来解析每一行的数据。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM