PDA

View Full Version : cin issues


php_brian
09-18-2003, 04:37 PM
i am having some issues with cin, but actually general input with both c and c++. i'm using c++ now for a program im writing.

i was helping my computer teacher with his c homework (a currency converter). basically what i was trying to do is validate the input, so my idea was to test the input against 0. i did a few tests to see what c was inserting in my float variable if i inputted a character. it outputted 0.000000. but it seems that isn't what it really is. im using a while loop to validate the input and if it is not correct then ask for it again until it is correct. but when i enter a character ill end up with an infinite loop. but if i were to enter something like 4a20 it just uses 4.00. here's what my code looks like in c++ since this seems to be the same between c and c++.


#include <iostream>

using namespace std;

void main(void) {
/* init variables */
float fAmount = 0;

/* get the amount from user */
do {
cout << "USD: ";
cin >> fAmount;
} while(fAmount <= 0);

cout << fAmount << endl;
}


so basically my question is...what exactly is it putting in fAmount if a character is inputted?

myjay610
09-19-2003, 01:46 AM
I really don't know.. but in side the while loop you should do a check to check that fAmount isn't <=0 OR not an integer.. there should be a function in ctype library or something that checks if a value is a float or not. off of the top of my head i can't think of it -- if you find another solution for this let me know cause I can't figure it out either.

n00b++
09-22-2003, 06:36 PM
Why do you need to put a character into fAmount? You should initilize it to char fAmount then. But then you would have to change around you while loop becuase chars have number values too.

stuka
09-23-2003, 11:31 AM
Originally posted by php_brian

so basically my question is...what exactly is it putting in fAmount if a character is inputted? The answer - nothing. Unless, of course, you have it set up to take hex input through the use of the <iomanip> header, in which case the chars a-f and A-F will be accepted. That's why 4a20 only gives you a 4 - the input stream sees that 'a' is not a digit, and stops reading.

Flangazor
09-24-2003, 12:39 PM
Clarification: cout and cin are not part of the C language so the code you posted was C++.

php_brian
09-24-2003, 10:18 PM
Yes, I know. I was referring to what I was doing with C, but I'm doing it in C++ here. I'm not expecting a char into the fAmount, but I want to be aware of anything that may come in.