[英]C++ reading string using more delimiters
I'm quite new to c++.我对 c++ 很陌生。 My problem is that I have a string that can be any length and ends with \n.
我的问题是我有一个可以是任意长度并以 \n 结尾的字符串。 For example:
例如:
const string s = "Daniel,20;Michael,99\n"
(It's always "name,age;name,age;name,age.............\n") const string s = "Daniel,20;Michael,99\n"
(始终是 "name,age;name,age;name,age.......\n")
and I want to separate name and age and put it into two vectors so it can be stored.我想将姓名和年龄分开并将其放入两个向量中以便可以存储。 But I dont know how to manage string with more separators.
但我不知道如何使用更多分隔符来管理字符串。 So the example would be separated like this:
所以这个例子会像这样分开:
Vector name contains {Daniel,Michael}向量名称包含 {Daniel,Michael}
Vector age contains {20,99}向量年龄包含 {20,99}
You can use stringstream
and getline
for this purpose, but since you have a very specific format, simple std::string::find
is likely to fix your issue.您可以为此目的使用
stringstream
和getline
,但由于您有一个非常特定的格式,简单的std::string::find
可能会解决您的问题。 Here is a simple example:这是一个简单的例子:
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstddef>
int main() {
std::string const s = "Daniel,20;Michael,99;Terry,42;Jack,34";
std::vector<std::string> names;
std::vector<int> ages;
std::size_t beg = 0;
std::size_t end = 0;
while ((end = s.find(',', end)) != s.npos) {
names.emplace_back(s, beg, end - beg);
char* pend;
ages.push_back(std::strtol(s.c_str() + end + 1, &pend, 10));
end = beg = pend - s.c_str() + 1;
}
for (auto&& n : names) std::puts(n.c_str());
for (auto&& a : ages) std::printf("%d\n", a);
}
Sorry my C++ skills have faded, but this is what I would do:-抱歉,我的 C++ 技能已经褪色,但这是我会做的:-
vector <string> names;
vector <string> ages;
string inputString = "Daniel,20;Michael,99;Terry,42;Jack,34";
string word = "";
for(int i = 0; i<inputString.length(); i++)
{
if(inputString[i] == ';')
{
ages.push_back(word);
word = "";
}
else if (inputString[i] == ',')
{
names.push_back(word);
word = "";
}
else
{
word = word + inputString[i];
}
}
ages.push_back(word);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.