【问题标题】:stringstream: taking multiple ints in a string and returning those to vectorstringstream:在一个字符串中获取多个整数并将它们返回给向量
【发布时间】:2021-01-04 10:37:48
【问题描述】:

我正在获取一个字符串并使用 stringstream 提取字符串中的整数,然后将它们推送到向量中。当我不一定知道字符串中整数的确切数量时,我的问题是这样做。该字符串可以是“23,45,68”,也可以是“-1,10,15,-22,199,12”。我的代码如下:

#include <sstream>
#include <vector>
#include <iostream>

using namespace std;

vector<int> parseInts(string str) {
    vector<int>v; 
    char ch;
    int a,b,c;
    stringstream s(str);
    s >> a >> ch >> b >> ch >> c;
    v.push_back(a);
    v.push_back(b);
    v.push_back(c);
    return v;
}

int main() {
    string str;
    cin >> str;
    vector<int> integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) {
        cout << integers[i] << "\n";
    }
    return 0;
}

【问题讨论】:

  • 使用while 循环读入一个临时的int 变量,并每次将其推入vector。在读取操作失败(即它没有要读取的内容)后,流转换为false,因此您可以将其用作循环条件。不过,您可能首先需要使用getline() 来读取cin,因为&gt;&gt; 将在第一个空格处停止,所以只需阅读第一个int
  • @BoBTFish 这看起来是一个不错的答案。你要创建一个吗?

标签: c++ stringstream


【解决方案1】:

我意识到当 while 循环点击字符串中的“,”时它正在结束。在循环中,我添加了将逗号放入字符持有者“ch”的代码这解决了问题:

#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

vector<int> parseInts(string str) {
    //cout << "str is " << str;
    vector<int>v;
    int x;
    char ch;
    stringstream num(str);
    while (num >> x)
    {
        num >>ch;   
        v.push_back(x); 
    }
    return v;
}

int main() {
    string str;
    cin >> str;
    vector<int> integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) {
        cout << integers[i] << "\n";
    }
    
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    相关资源
    最近更新 更多