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

Using getline to divide input, using commas as delim

我有一个包含电影信息的文本文件,以逗号分隔。我将提供一行以供深入了解:

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

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

void addMovieNode(int ranking, std::string title, int releaseYear, int quantity);

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

我知道我可以像

一样传入文本文件
getline("moveInfo.txt", string, ",");

但这将如何转化为输出的实际情况?

我阅读了 cplusplus 网站上的手册,但这对澄清没有多大帮助。

您可以使用 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; } 
}