2

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

所以一旦我有了一个整数向量,就有了 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;
}
4

2 回答 2

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;
}

顺便说一句,ctrl-D或非整数输入,如char,将终止 this while

于 2013-05-05T04:18:47.390 回答
1

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);
于 2013-05-05T04:19:00.573 回答