如何从CSV文件中获取数据,并将数据解析为两个逗号之间的INT?

时间:2017-07-31 23:10:45

标签: c++ string parsing

首先,对这个问题的具体方式表示道歉,因为这是我第一次提出StackOverflow的问题。

我将开始工作,我正在开发一个项目,该项目会读取一个文件(特别是CSV),然后将某些数据从那里保存到Int中,稍后我会搞砸。

基本上,我的代码目前如下:

            if (!infile) {
            cout << "You entered something that cannot be opened, please try again." << endl;
            Continue = true;
        }
        else {
            while (infile.good()) {
                getline(infile, value, ','); // read a string until next comma
                cout << string(value, 1, value.length() - 2); // display value removing the first and the last character from it
            }
            Continue = false;
        }
    }

到目前为止,它读取数据并输出如下所示的行:

    2014-01-03,"2014","01","03","†","-12.8","","-31.0","","-21.9","","39.9","","0.0","","","M","","M","0.0","","","","","","<31",""
2014-01-04,"2014","01","04","†","-2.3","","-12.8","","-7.6","","25.6","","0.0","","","M","","M","2.9","","40","","18","","39",""
2014-01-05,"2014","01","05","†","-2.1","","-4.1","","-3.1","","21.1","","0.0","","","M","","M","16.2","","52","","8","","32",""

我需要的信息是在第5个和第6个逗号之间(它表示当天的平均温度),我不知何故需要将这两个逗号之间的信息放入某种int中。

同样,第3个和第4个逗号之间是一天,我稍后需要计算每个月的平均温度,所以我也需要弄明白。

有谁知道这样做的正确方法?不幸的是,我需要了解字符串解析。

1 个答案:

答案 0 :(得分:0)

据我了解,您想知道如何从字符串中获取整数值。

如果C ++ 11可用,那么你应该使用stoi函数(http://www.cplusplus.com/reference/string/stoi/http://en.cppreference.com/w/cpp/string/basic_string/stol)。如果不是,出于某种原因,请使用atoi一个(http://www.cplusplus.com/reference/cstdlib/atoi/)。

以下主题似乎很有用: http://www.cplusplus.com/forum/general/13135/ https://www.quora.com/How-do-I-convert-a-string-into-an-integer-in-C++

PS。确保您的字符串不包含不需要的字符(例如\“或者左右)