0

我面临一个问题,如何从输入流中读取空格分隔的数据。

假设我们需要输入 J 123 7 3 M。第一个是字母,最后一个是字母。其余的是整数。

vector<int> ints;
vector<char> chars;
stringstream ss;

...

cin >> c
chars.push_back(c);
ss << c;
cin >> i;
while(ss << i) {
    ints.push_back(i);
}

...

但是这段代码并不能解决问题。我尝试了很多组合,但仍然没有。

我在想我可以将所有内容都读取为 char,然后将其转换为 int。

我知道有类似的问题,但就我而言,我想在没有字符串而不是动态数组的情况下解决这个问题(可能是动态数组但没有设定长度)。

编辑

我设法通过以下方式阅读了这样的stram:

char first, last;
int i;

std::cin >> first;
std::cout << first;

while(std::cin >> i) {
    std::cout << i;
}

std::cin >> last;
std::cout << last;

但是有一个问题:写“F 1 23 2 2 W”会显示F12322@。不知道为什么最后有“@”。有什么想法吗?

编辑2:

std::cin.clear();

在while循环解决问题之后。

4

2 回答 2

1

如果您知道元素的数量及其类型,那么您可以使用以下代码

#include<vector>
#include<iostream>

using namespace std;

int main()
{
    int i;
    char c;
    vector<int> ints;
    vector<char> chars;

    cin>>c;
    chars.push_back(c);
    for(int j=0;j<3;j++){
        cin>>i;
        ints.push_back(i);

        }
    cin>>c;
    chars.push_back(c);
}
于 2015-01-17T14:26:03.877 回答
1

为了组织和添加您的数据,您可以创建一个小结构,operator>>例如(ideone):

struct line{
    char f1,f5;  // give them meaningful names
    int f2,f3,f4;
    friend std::istream &operator>>(std::istream &is, line &l) {
        is >> l.f1;
        is >> l.f2;
        is >> l.f3;
        is >> l.f4;
        is >> l.f5;
        return is;
    }
};


int main() {
    string input = "J 123 7 3 M\nK 123 7 3 E\nH 16 89 3 M";
    stringstream ss(input);
    vector<line> v;
    line current;

    while(ss >> current){
        v.push_back(current);
    }
    for (auto &val: v){
        cout<< val.f1 << endl;
    }
    return 0;
}

每次你读到一些东西时,你都可以对这条线做任何你想做的事情current。如果每个留置权没有特定的含义,你可以做一个

while(ss>>f1>>f2>>f3>>f4>>f5){    
    // do stuff with fields
}

哪里ss是 astringstream但它可能都是这样cin

于 2015-01-17T14:10:39.193 回答