将字符串解析为int

时间:2013-05-05 04:14:26

标签: c++ linked-list tokenize istringstream

我对编码很陌生,我希望有人可以帮助我吗?我试图读取一行空格分隔的整数,并将它们解析为(最终进入链表)一个向量。

所以一旦我有一个int的向量,就会有STL向量的迭代器,但是如何迭代不在STL中的链接列表中的节点?

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

using namespace std;

int main(int argc, char** argv) {    
    cout << "Enter some integers, space delimited:\n";
    string someString;
    getline(cin, someString);

    istringstream stringStream( someString );
    vector<string> parsedString;
    char splitToken = ' ';

    //read throguh the stream
    while(!stringstream.eof()){
        string subString;
        getline( stringStream, subString, splitToken);
        if(subString != ""){
        parsedString.push_back(subString);
        }
   }

    return EXIT_SUCCESS;
}

2 个答案:

答案 0 :(得分:1)

由于它是空间分隔符,为什么不只是:

#include <iostream>
using namespace std;

int main() {
    int a;
    vector<int> v;
    while (cin >> a) {
        v.push_back(a);
    }

    for (int i = 0; i < v.size(); ++i) {
        int b = v[i];
    }

    return 0;
}

BTW,ctrl-D或非整数输入(例如char)将终止此while

答案 1 :(得分:0)

stringstream可以自动处理这样的分隔符:

cout << "Enter some integers, space delimited:\n";
string someString;
getline(cin, someString);

istringstream stringStream( someString );
vector<int> integers;
int n;
while (stringStream >> n)
    integers.push_back(n);