使用getline划分输入,使用逗号作为delim

时间:2016-10-11 21:14:49

标签: c++ getline

我有一个带有电影信息的文本文件,以逗号分隔。我将提供一个洞察力线:

my $id = 0;

my $name = getgrgid($id);
print("$name\n");

我需要使用这一行,并用逗号分隔不同的部分以符合此函数的格式:

8,The Good the Bad and the Ugly,1966,2

文本文件的信息与函数有关,但我不清楚getline操作是如何运作的。

我知道我可以传入像

这样的文本文件
void addMovieNode(int ranking, std::string title, int releaseYear, int quantity);

但是如何根据输出的实际情况进行转换?

我在cplusplus网站上阅读了手册,但这无助于澄清。

1 个答案:

答案 0 :(得分:1)

您可以使用stringstringstream

#include <sstream>
#include <string>
#include <fstream>

ifstream infile( "moveInfo.txt" );    
while (infile)
{
    std::string line;
    if (!std::getline( infile, line,',' )) break;
    std::istringstream iss(line);
    int ranking, releaseYear, quantity;
    std::string title;
    if (!(iss >> ranking >> title >> releaseYear >> quantity)) { break; } 
}