如何只读取C ++中.csv文件每行的第一个值?

时间:2018-01-26 19:09:06

标签: c++

我想使用while循环将.csv文件的每一行的第一个值放在C ++中的变量中,然后将其打印出来。输出是这样打印的每一行的第一个值。

我的数据是(如.cssv文件中)

Mike,22,Student
James,54,Engineer
Lily,23,Student

我想在每次迭代中将名称放在变量中然后打印它。我的输出只是这些名称的列表。

1 个答案:

答案 0 :(得分:1)

您可以使用std::stringstreamstd::getline来获取名字,如下所示:

std::string str;
std::vector <std::string> result;       // Vector of names

while( std::getline( std::cin, str ) )  // replace std::cin, with file input stream
{
    std::stringstream ss(str);
    if( ss.good() )
    {
        std::string substr;
        std::getline( ss, substr, ',' ); // Grab first names till first comma
        result.push_back( substr );      // Push into the vector
    }
}

Demo Here