我可以在C ++函数getline中使用2个或更多定界符吗? [英] Can I use 2 or more delimiters in C++ function getline?
问题描述
我想知道如何在getline函数中使用2个或更多定界符,这是我的问题:
I would like to know how can I use 2 or more delimiters in the getline functon, that's my problem:
程序读取一个文本文件...每一行都像是这样:
The program reads a text file... each line is goning to be like:
New Your, Paris, 100
CityA, CityB, 200
我使用的是getline(file,line),但是当我想要获取CityA,CityB和号码时,我得到了整行.如果我使用','分隔符,我将不知道何时是下一行,所以我正在尝试找出解决方案..
I am using getline(file, line), but I got the whole line, when I want to to get CityA, then CityB and then the number; and if I use ',' delimiter, I won't know when is the next line, so I'm trying to figure out some solution..
但是,如何使用逗号和\ n作为分隔符?顺便说一下,我正在操纵字符串类型,而不是char,所以strtok不可能:/
Though, how could I use comma and \n as a delimiter? By the way,I'm manipulating string type,not char, so strtok is not possible :/
一些划痕:
string line;
ifstream file("text.txt");
if(file.is_open())
while(!file.eof()){
getline(file, line);
// here I need to get each string before comma and \n
}
推荐答案
您可以使用 std :: getline
读取一行,然后将该行传递给
You can read a line using std::getline
, then pass the line to a std::stringstream
and read the comma separated values off it
string line;
ifstream file("text.txt");
if(file.is_open()){
while(getline(file, line)){ // get a whole line
std::stringstream ss(line);
while(getline(ss, line, ',')){
// You now have separate entites here
}
}
这篇关于我可以在C ++函数getline中使用2个或更多定界符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!