[英]C++ Tokenize part of a String
Trying to tokenize a String in C++ which is read from a file, separated by commas, but I only need the first 3 data of every line. 试图标记从文件读取的C ++中的字符串,用逗号分隔,但我只需要每行的前3个数据。
For example: The lines look like this: 例如:这些行如下所示:
140,152,2240,1,0,3:0:0:0: 140,152,2240,1,0,3:0:0:0:
156,72,2691,1,0,1:0:0:0: 156,72,2691,1,0,1:0:0:0:
356,72,3593,1,0,1:0:0:0: 356,72,3593,1,0,1:0:0:0:
But I only need the first 3 data of these lines. 但是我只需要这些行的前3个数据。 In this case:
在这种情况下:
140, 152, 2240 140、152、2240
156, 72, 2691 156、72、2691
356, 72, 3593 356、72、3593
I'm trying to add these data into a vector I just don't know how to skip reading a line from the file after the first 3 data. 我正在尝试将这些数据添加到向量中,我只是不知道如何跳过前3个数据之后从文件中读取一行。
This is my current code: (canPrint is true by default) 这是我当前的代码:(默认情况下canPrint为true)
ifstream ifs;
ifs.open("E:\\sample.txt");
if (!ifs)
cout << "Error reading file\n";
else
cout << "File loaded\n";
int numlines = 0;
int counter = 0;
string tmp;
while (getline(ifs, tmp))
{
//getline(ifs, tmp); // Saves the line in tmp.
if (canPrint)
{
//getline(ifs, tmp);
numlines++;
// cout << tmp << endl; // Prints our tmp.
vector<string> strings;
vector<customdata> datalist;
istringstream f(tmp);
string s;
while (getline(f, s, ',')) {
cout << s << " ";
strings.push_back(s);
}
cout << "\n";
}
How about checking the size of the vector first? 首先检查向量的大小如何? Perhaps something like
也许像
while (strings.size() < 3 && getline(f, s, ',')) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.