c++ - sstream 不填充 vector C++

标签 c++ vector sstream

在命令行中输入:

1 2 3

它存储在“”中,我的 vector 只填充了

1

我做错了什么? 这是代码

string line;
    string buffer;
    int a,b,base;

    cin >> line;
    stringstream ss(line);
    std::vector<string> tokens;
    while( ss >> buffer){
        tokens.push_back(buffer);
    }
    for(int i=0; i<tokens.size(); i++){cout << tokens[i] << endl;}

最佳答案

你的问题在这里:

cin >> line;

注意这个函数

operator>>(istream& is, string& str)

获取所有字符,直到第一次出现空格(在输入 1 2 3 的情况下,它在 1 之后的空格处停止)

尝试使用函数 getline(),它读取字符串直到第一次出现换行符。

这似乎可行:

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

using namespace std;

int main(void) {
    string line;
    string buffer;
    int a,b,base;

    getline(cin, line);
    stringstream ss(line);
    vector<string> tokens;
    while( ss >> buffer){
        tokens.push_back(buffer);
    }
    for(int i=0; i<tokens.size(); i++){cout << tokens[i] << endl;}

    return 0;
}

关于c++ - sstream 不填充 vector C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31932349/

相关文章:

C++ std::vector<std::string> 迭代器段错误

c++ - (C++) 无法从我的堆栈对象调用 push() 和 pop()

c++ - 在 leveldb 的 c++ 示例中声明迭代器时出现段错误

g++ - g++编译错误: missing ';'

c++ - 将带有引号和逗号的字符串文件读入字符串数组

c++ - 调用列表中子对象方法的最佳方法?

c++ - 使用 Vectors 创建对象时如何调用析构函数

C++ std::random 和枚举类

c++ - itoa 在 C++ 中创建一个无限循环

c++ - 使用多线程解析c++字符串