-2

I am having issues getting an input line of comma-delimited numbers to properly pass into a double vector.

I'm mildly new to C++ and am in a bit of a pickle. I've tried using a double array, but double vectors seem to work better.

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) << ", ";
    }

}

The whole numbers seem to pass fine, but if I include a decimal (I.E. 1.4), the decimal is not include. There are no error messages. How can I fix this?

CurlyCue
  • 35
  • 1
  • 2

1 Answers1

1

You are using an integer to read from ss (int i;). An integer cannot contain decimal points or fractions. Change it to double and you will be fine. Also std::vector is almost always preferrable over plain arrays.

Note that in your last for loop, you can also use the subscript operator to access the vector elements:

for (int j = 0; j < vect.size(); j++){
    cout << vect[j] << ", ";
}
Timo
  • 9,269
  • 2
  • 28
  • 58
  • Thank you! I can't believe I overlooked that. I have a habit of missing one minor detail and blowing up my project. – CurlyCue Aug 25 '19 at 20:36