K
Keith Thompson
Xancatal said:Thanks Neil, how do you think I could convert it? I tried this and it
failed during compile time:
float myVar = 0.0;
...
...
...
scanf ("%c", &otherVar);
The "%c" format expects a pointer to the first element of a character
array. With no length specified, the length defaults to one. A
single character object, in this context, acts like an array of length
one. You didn't show us the declaration of otherVar, but for this to
work, it should be of type char. So this is a (somewhat convoluted)
way to read a single character.
myVar = &otherVar;
It looks as although I tried to assign the value of this string to the
float, it fails compilation. It says it can not assign value.
&otherVar is the address of your char variable, so it's of type char*
(pointer-to-char). You can't assign a char* to a float; it doesn't
even make sense to try.
Part of the problem is that there are multiple ways to do what you're
trying to do.
One of the most general ways to handle text input is:
Use fgets() to read a whole line at a time into a string. Note
that the resulting string will usually contain the '\n' character
that terminated the line. (If the input line is longer than your
buffer, or if you hit end-of-file or an error, things can get more
complicated.)
Use sscanf(), or perhaps some more specific function like
strtol(), to extract the data from the string.
You *can* use scanf(), but it combines reading input and parsing it
("parsing" means analyzing data in a sequence of characters, either a
string or an input file), and it doesn't respond well to errors.
Using fgets() and sscanf() separately, if sscanf() fails, you can
easily discard the entire line, or try again with a different format.
scanf() or fscanf() is less flexible; if there's an error, it's
already consumed some amount of input.