将字符串解析为C++;? 最近我开始学习C++,而且我还很难适应其他语言。我相信有一个更简单的解决方案,但我不明白为什么这不起作用

将字符串解析为C++;? 最近我开始学习C++,而且我还很难适应其他语言。我相信有一个更简单的解决方案,但我不明白为什么这不起作用,c++,string,C++,String,基本上,我需要一种方法将输入(如566193(整数的未知长度))转换为向量/其他内容,如“[566193]” 这是我的代码: vector<int> A; string AToParse; getline(cin, AToParse); int pos = 0; while (pos < AToParse.length()) { if (AToParse[pos] == ' ') { pos++; continue; }

基本上,我需要一种方法将输入(如
566193
(整数的未知长度))转换为向量/其他内容,如“
[566193]

这是我的代码:

vector<int> A;
string AToParse;
getline(cin, AToParse);
int pos = 0;
while (pos < AToParse.length()) {
    if (AToParse[pos] == ' ') {
        pos++;
        continue;
    }
    string tmp = "" + AToParse[pos];
    if (pos + 1 >= AToParse.length()) break;
    for (int i = pos + 1; i < AToParse.length(); i++) {
        if (AToParse[i] == ' ') {
            pos = i + 1;
            break;
        } else {
            tmp += AToParse[i];
        }
    }
    int tmpint = stoi(tmp);
    A.push_back(tmpint);
}
for (int Ai : A) {
    cout << Ai << endl;
}
向量A;
字符串解析;
getline(cin,atoprase);
int pos=0;
while(pos=AToParse.length())中断;
for(inti=pos+1;i#包括
s:


从C++17开始,您可以删除对
std::vector
类型名的额外重复。由于C++17中称为类模板参数推断(CTAD)的新功能,它将从迭代器中正确推断出来根据“不重复自己”规则,您必须只提及一次希望从字符串中读取的类型:

std::stringstream parseStream{atoprase};
std::向量A(std::istream_迭代器{parseStream},{});

但是请注意,只有当您使用括号作为
std::vector
初始值设定项时,这才会达到预期效果。使用括号括起的初始值设定项列表时,这不会起到正确的作用。

我在编写答案时可能误读了您的问题。如果您正在寻找代码调试帮助,请添加示例输入/o您的代码生成的输出和/或它向您发出的错误消息。在我的回答中,我向您展示了“更简单的解决方案”。
std::stringstream parseStream{AToParse};
std::vector<int> A(std::istream_iterator<int>{parseStream}, std::istream_iterator<int>{});
std::stringstream parseStream{AToParse};
std::vector<int> A(std::istream_iterator<int>{parseStream}, {});
std::stringstream parseStream{AToParse};
std::vector A(std::istream_iterator<int>{parseStream}, {});