C ++标记字符串的一部分
C++ Tokenize part of a String
尝试在 C++ 中标记从文件中读取的字符串,用逗号分隔,但我只需要每行的前 3 个数据。
例如:
这些行看起来像这样:
140,152,2240,1,0,3:0:0:0:
156,72,2691,1,0,1:0:0:0:
356,72,3593,1,0,1:0:0:0:
但我只需要这些行的前 3 个数据。在这种情况下:
140, 152, 2240
156, 72, 2691
356, 72, 3593
我正在尝试将这些数据添加到一个向量中我只是不知道如何在前 3 个数据之后跳过从文件中读取一行。
这是我当前的代码:(canPrint 默认为真)
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";
}
先检查向量的大小如何?也许像
while (strings.size() < 3 && getline(f, s, ',')) { ... }
尝试在 C++ 中标记从文件中读取的字符串,用逗号分隔,但我只需要每行的前 3 个数据。
例如:
这些行看起来像这样:
140,152,2240,1,0,3:0:0:0:
156,72,2691,1,0,1:0:0:0:
356,72,3593,1,0,1:0:0:0:
但我只需要这些行的前 3 个数据。在这种情况下:
140, 152, 2240
156, 72, 2691
356, 72, 3593
我正在尝试将这些数据添加到一个向量中我只是不知道如何在前 3 个数据之后跳过从文件中读取一行。
这是我当前的代码:(canPrint 默认为真)
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";
}
先检查向量的大小如何?也许像
while (strings.size() < 3 && getline(f, s, ',')) { ... }