Search code examples
c++stringparsinginputstringstream

Parse a stringstream into strings and doubles


I am writing a program that takes inputs on one line as follows:

Run 10.1 50.2

Where "Run" is a string and the rest of the line are doubles. Scientific notation and negative numbers can also be used as double inputs: -5.88e-11 for example (Standard C++ library allows this).

Here is the initial code I tried.

string command; 
double input1; 
double input2; 
getline(cin,input);
stringstream ss(input);

ss >> command >> input1 >> input2;

The problem with this approach is that if a blank space or a letter is input in the place of a double the output of the stringstream will be 0. I believe this is because there are no null holders for double in C++.

Another approach I tried is to read each input as a string, check that the string is numerical and convert it to a double. However, this becomes complicated when scientific notation and negatives can be entered. Attempt at this:

for (int i=0; input1[i]; i++){
    if (isdigit(input1[i])){\
        isDigit = true;
    }else{
        isDigit = false;
    }
}

How can I parse this input with a string and alphanumerical doubles on the same line? (while retaining negatives and scientific notation)

Thanks!


Solution

  • Using std::cin directly and checking if there's any error in parsing the stream.

    std::string command;
    double arg1, arg2;
    
    if (std::cin >> command >> arg1 >> arg2) {
        std::cout << command << std::endl;
        std::cout << arg1 << std::endl;
        std::cout << arg2 << std::endl;
    } else {
        // error!
    }