这个问题有很多潜在的解决方案。一个相当普遍的做法是:
- 首先将一个完整的行读入一个字符串
- 将字符串放入
std::istringstream,这样你就可以使用io函数从那里提取数据
- 使用带有分隔符的函数
std::getline 从std::istringstream 中读取,直到看到分隔符
- 再次执行相同的步骤以进一步拆分先前拆分的部分。
在第一种情况下,沿冒号拆分,然后沿逗号拆分
在第二种情况下,沿逗号拆分,然后沿“@”拆分结果部分
请阅读here 关于std::getline。
一种潜在的解决方案可能如下所示:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <vector>
std::istringstream test{ R"(ram:30,40,50
honda@30,tvs@30)" };
int main() {
// Read a complete line
std::string line{}; std::getline(test, line);
// Put the line into a std::istringstream to extract further parts
std::istringstream iss1(line);
// Use std::getline to extract something until you see a separator
std::string identifier{};
std::getline(iss1 >> std::ws, identifier, ':');
std::cout << identifier << '
';
// Now extract all numbers
std::string number{};
while (std::getline(iss1 >> std::ws, number, ','))
std::cout << number << '
';
// Get the complete second string
std::getline(test, line);
// Split the string into parts until you see a comma
std::vector<std::string> parts{};
// Put the line into a std::istringstream to extract further parts
std::istringstream iss2(line);
while (std::getline(iss2 >> std::ws, identifier, ','))
parts.push_back(identifier);
// Now all parts are stored in a vector
// Then let us split the single parts further
for (const std::string& part : parts) {
std::cout << '
';
std::istringstream iss3(part);
std::getline(iss3, identifier, '@');
std::cout << identifier << '
';
std::getline(iss3, number);
std::cout << number << '
';
}
}
还有更高级的技术,但现在,请尝试理解以上内容。