| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Data Stream Question
Hi Gang,
In C++, I want to query the user for a bunch of different variables. BUT, if they only hit enter (with no values typed), I want the program to keep the default value. Here is what I've tried (don't laugh too hard at my code, I'm a noob): double ts; cout<<"Time increment ["<<time_step<<"]: "; ts = cin.get (); if (ts == '\0') time_step = ts; cout<<time_step<<endl; I know just a plain enter will not result in a null character, but I don't know what else to try. I've tried if (!cin.get()), then cin>>time_step. I assume a better understanding of how the data stream works in C would help, which is why I'm coming to this board! Thanks! |
|
#2
|
||||
|
||||
|
Code:
if (ts == 10) If you only hit <Enter>, then a "line feed", with ASCII value 10, will stored in the variable.... thus, just check to see if the variable's value is 10, if so they may have just pressed <Enter>.... however, this obviously leaves the problem of the user legitimately entering 10 as their choice, as you'd have no way to distinguish the two... Thus, I recommend reading their choice in as a string then converting it to a float using atof().... actually, I would recommend processing all user-input as strings then converting it as needed hth
__________________
Officially a member of the Itsacon fan club. Beer blasts are every friday at Viper_SB's house. I bring the chips. ![]() |
|
#3
|
|||
|
|||
|
Can you convert strings to double?
|
|
#4
|
|||
|
|||
|
AH-HA! I got it! Here is the solution:
char ts[256]; double n; cout<<"Time increment ["<<time_step<<"]: "; gets (ts); n = atof (ts); if (ts[0] != '\0') time_step = n; cout<<time_step<<endl; Pretty cool, huh? I have to give props to B-Con and cplusplus.com Hope you all have a good day. I know I will now! |
|
#5
|
||||
|
||||
|
hth, always feels good to solve a problem, doesn't it
![]() |
|
#6
|
|||
|
|||
|
Yes strings can be converted to doubles!!!
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Data Stream Question |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|