Get user input displaying default value

Hi,

I would like to get user input of some parameters value (mostly of type "double", but few of type "int") but displaying the default value at the place of input.

If the user does not want to modify the value, he types "Enter" to pass; if the use wants to modify the value, he enters a new value at the place of the value by default, then types "Enter" to pass to the next parameter.

Here is a simplified example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main() {
   double a = 1.5;
   double b = 2.5;
   double c = 3.5;
   double x;

   cout << "Please confirm or modify the following parameters:" << endl;
   cout << "a = " << a;     // display the value by default
   getline(cin, x);         // receive user input
   if(!x.empty()){          // check whether input is empty
      a = x;
   }
   cout << endl;

   // do the same for b and c...

   cout << "sum = " << a + b + c << endl; // display the result

   return 0;
}

However, this does not work. getline() cannot take double type, and I do not know whether the rest of the code is good and efficient.

Could anyone please help me? Thanks a lot!
Last edited on
there is no empty() method you can call on a double..

example of getline() here: http://www.cplusplus.com/reference/istream/istream/getline/
Last edited on
Yes I know. That's my question. How can I get input of double and check whether the input is empty or not?
if you want to use getline, you should use it like this:
cin.getline(parameter,256);

where you need to declare 'parameter' as a char array NOT as a double in your case. you could use stringstreams too.

if the user just presses enter the size of this string is zero. Use that to test with.

You also need to consider if the user, for some reason, enters a non-numerical string.

Also, your code will only work once. You need some kinda loop there so the user can enter parameters more than once.
Thanks for the reply. Is there a way to get input of double directly, instead of convert it from char to double, and be able to check whether the user entered a value or just typed Enter key?
Is that possible to display all three parameters (one per line) and allow the user to move from one parameter to another (one line to another) with his arrow key in keyboard to modify any parameter's value?

Thanks!
nah it's not. well i dont think so. I another languages like c# you have Parse and TryParse, which will automatically assume the user is entering a double for example and return false or throw an exception if it isnt a double.

have a google on stringstreams. might be better to use one of them.
Topic archived. No new replies allowed.