首页 > 解决方案 > 将输入流转换为双向量

问题描述

我在获取逗号分隔数字的输入行以正确传递到双向量时遇到问题。

我对 C++ 还比较陌生,而且有点吃不消。我试过使用双数组,但双向量似乎效果更好。

int main(){
    vector<double> vect;
    string input1;
    string token;
    int i;
    int size;
    cout << "Please input up to 1000 comma-delimited numbers (I.E. '5,4,7.2,5'): ";
    cin >> input1;
    stringstream ss(input1);


    while (ss >> i){
        vect.push_back(i);
        if (ss.peek() == ','){
            ss.ignore();
        }
    }

    for (int j = 0; j < vect.size(); j++){
        cout << vect.at(j) << ", ";
    }

}

整数似乎可以通过,但如果我包含小数(IE 1.4),则不包含小数。没有错误消息。我怎样才能解决这个问题?

标签: c++visual-studiovectorstringstream

解决方案


您正在使用整数从ss( int i;) 中读取。整数不能包含小数点或分数。将其更改为double,您会没事的。也std::vector几乎总是比普通数组更可取。

请注意,在最后一个 for 循环中,您还可以使用下标运算符来访问向量元素:

for (int j = 0; j < vect.size(); j++){
    cout << vect[j] << ", ";
}

推荐阅读