使用getline分隔输入,使用逗号作为分隔符

Using getline to divide input, using commas as delim

本文关键字:分隔符 getline 分隔 输入 使用      更新时间:2023-10-16

我有一个带有电影信息的文本文件,用逗号分隔。我将提供一行深入的见解:

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