Store a char into an integer variable

O

obdict

Hello, I have a simple C question regarding scanf()

/* What happens if user inputs a char when he/she is supposed
* to input an integer?
*/

#include<stdio.h>

int main(void){
int n;
printf("Please enter an integer:\n");
scanf("%d", &n);
printf("n is %d.\n", n);

return 0;
}
_____________________

../a.out

Please enter an integer:
Awheofhoeafh
n is 2468992

Any non-integer will result in this magic number 2468992 on my
lab workstation, no matter what non-integer value I provided to it.
Here's some hardware spec.

spidermn:/>cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 15
model : 4
model name : Intel(R) Pentium(R) 4 CPU 2.80GHz
stepping : 1
cpu MHz : 2793.823
cache size : 1024 KB
fdiv_bug : no
hlt_bug : no
f00f_bug : no
coma_bug : no
fpu : yes
fpu_exception : yes
cpuid level : 5
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge
mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe pni
monitor ds_cpl cid xtpr
bogomips : 5537.79

I had thought if I input uppercase A, its ASCII code 65 will be output.
In reality, I still got that magic number.

On a different machine in the same room, though, random strings of
characters produced different negative integer each time.

Any idea why? Thanks in advance.
 
R

Robert Harris

obdict said:
Hello, I have a simple C question regarding scanf()

/* What happens if user inputs a char when he/she is supposed
* to input an integer?
*/

#include<stdio.h>

int main(void){
int n;
printf("Please enter an integer:\n");
scanf("%d", &n);
printf("n is %d.\n", n);

return 0;
}
_____________________

./a.out

Please enter an integer:
Awheofhoeafh
n is 2468992

Any non-integer will result in this magic number 2468992 on my
lab workstation, no matter what non-integer value I provided to it.
Here's some hardware spec.

spidermn:/>cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 15
model : 4
model name : Intel(R) Pentium(R) 4 CPU 2.80GHz
stepping : 1
cpu MHz : 2793.823
cache size : 1024 KB
fdiv_bug : no
hlt_bug : no
f00f_bug : no
coma_bug : no
fpu : yes
fpu_exception : yes
cpuid level : 5
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge
mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe pni
monitor ds_cpl cid xtpr
bogomips : 5537.79

I had thought if I input uppercase A, its ASCII code 65 will be output.
In reality, I still got that magic number.

On a different machine in the same room, though, random strings of
characters produced different negative integer each time.

Any idea why? Thanks in advance.
Because that was in n before your scanf call. (try checking the return
value of scanf)

Robert
 
O

obdict

Thanks for the reply.

I entered "Awheofhoeafh" at the prompt and got that number.
If I enter other character strings, it still outputs the same number.
And how is a string *converted* to integer during the scanf() call?
 
J

Jordan Abel

Hello, I have a simple C question regarding scanf()

/* What happens if user inputs a char when he/she is supposed
* to input an integer?
*/

#include<stdio.h>

int main(void){
int n;
printf("Please enter an integer:\n");
scanf("%d", &n);
printf("n is %d.\n", n);

return 0;
}
_____________________

./a.out

Please enter an integer:
Awheofhoeafh
n is 2468992

scanf does not modify the integer variable if it is not given an
integer. 2468992 is just whatever was already in n before.
 
L

Lew Pitcher

obdict said:
Thanks for the reply.

I entered "Awheofhoeafh" at the prompt and got that number.
If I enter other character strings, it still outputs the same number.
And how is a string *converted* to integer during the scanf() call?

The entered string /isn't/ being converted to an integer. In fact, the
entered string isn't being read by the program at all.

You gave us
#include<stdio.h>

int main(void){
int n;
printf("Please enter an integer:\n");
scanf("%d", &n);
printf("n is %d.\n", n);

return 0;
}

In this code, you use scanf() to read your data. You give scanf() a
format string of "%d", which tells scanf() expect a numeric input. /If/
you do not give scanf() numbers, then it cannot satisfy the format
string requirements, and scanf() will
a) leave the unset variables unset, and
b) return a value indicating the number of variables set
In your case, if you enter "Awheofhoeafh" (or any other non-numeric
data), your scanf() will return 0, and leave n unset.

So, when you print the value of n, you get the data that was last put in
n. Since n was uninitialized, you got garbage.

HTH
--

Lew Pitcher, IT Specialist, Corporate Technology Solutions,
Enterprise Technology Solutions, TD Bank Financial Group

(Opinions expressed here are my own, not my employer's)
 
O

obdict

Do you mean scanf() will discard input if it is not compatible with the
format (in this case %s vs. %d)?

But on a different machine (Fedora Core Test 3), I got different
results (negative
integer) for different input (random character strings).

Thanks
 
J

Jordan Abel

Do you mean scanf() will discard input if it is not compatible with the
format (in this case %s vs. %d)?

But on a different machine (Fedora Core Test 3), I got different
results (negative
integer) for different input (random character strings).

Coincidence. n had different stuff in it before scanf each time.
 
R

Robert Harris

obdict said:
Do you mean scanf() will discard input if it is not compatible with the
format (in this case %s vs. %d)?

No, it isn't discarded. It just hasn't been "consumed" yet, in the sense
that the next read from stdin will start reading from the string.

Robert
 
M

Mike Wahler

obdict said:
Hello, I have a simple C question regarding scanf()

/* What happens if user inputs a char when he/she is supposed
* to input an integer?
*/

All stream input is in characters. If the characters
are not numeric digits when scanf() reads a "%d"-specified
field, scanf() fails. The characters remain in the input
stream, and the 'target' object is unchanged.
#include<stdio.h>

int main(void){
int n;
printf("Please enter an integer:\n");
scanf("%d", &n);

If scanf()'s return value is not == 1, then 'n'
is not changed. Since you didn't initialize or
assign 'n' a value it will not be guaranteed to
hold a valid value. You did not check scanf()'s
return value, yet your code proceeds as if 'n'
has a valid value.
printf("n is %d.\n", n);

return 0;
}
_____________________

./a.out

Please enter an integer:
Awheofhoeafh
n is 2468992

Any non-integer will result in this magic number 2468992

Or any other behavior. The behavior is undefined, since 'n'
was never initialized or assigned a valid value, and it
was evaluated.
on my
lab workstation, no matter what non-integer value I provided to it.
Here's some hardware spec.

<snip>

None of that is relevant, since C is platform-neutral.
I had thought if I input uppercase A, its ASCII code 65 will be output.

You cannot assume a particular character set with portable code.

Why would you expect that output? "%d" expects digit characters,
you didn't supply any. scanf() failed. You should *always* check
the return value before attempting to use any values you try to
store with scanf().

In reality, I still got that magic number.

You could have got anything else, some other number, no
number, the number you expected, a crash, etc. etc. The
behavior is undefined.
On a different machine in the same room, though, random strings of
characters produced different negative integer each time.

That is the nature of undefined behavior.
Any idea why?

I think you misunderstand how scanf() works. Review a good C text.

Finally, the common recommended way to read numeric input is to
read it as a string (e.g. with fgets()), then validate it (e.g.
with 'strtol()'.

-Mike
 
L

Lew Pitcher

obdict said:
Do you mean scanf() will discard input if it is not compatible with the
format (in this case %s vs. %d)?

Nope. I mean that scanf() /will not consume/ input if it is not
compatible with the format string. The input remains "in the queue"
waiting to be read by a scanf() (or other suitable stdio call) that
/can/ consume it.

In other words, the first time you use scanf("%d",&n) on your "abc123"
string, scanf() will not read "abc123", leaves n unaltered, and returns 0.

The /next time/ you use scanf("%d",&n), it will again try to consume the
outstanding "abc123" string, and again will fail.

This will continue until your program changes tactics, and consumes the
outstanding data through some other means (i.e. scanf("%*s") or
getchar() or other).

But on a different machine (Fedora Core Test 3), I got different
results (negative
integer) for different input (random character strings).

That's because n had garbage in it to start, and was never altered from
that garbage because of the failure of your scanf().

That the garbage in n was different system to system (or even run to
run) is to be expected.

--

Lew Pitcher, IT Specialist, Corporate Technology Solutions,
Enterprise Technology Solutions, TD Bank Financial Group

(Opinions expressed here are my own, not my employer's)
 
C

CBFalconer

obdict said:
Hello, I have a simple C question regarding scanf()

/* What happens if user inputs a char when he/she is supposed
* to input an integer?
*/

#include<stdio.h>

int main(void){
int n;
printf("Please enter an integer:\n");
scanf("%d", &n);
printf("n is %d.\n", n);

return 0;
}
.... snip ...

Any idea why? Thanks in advance.

You haven't bothered to check the return value of scanf. That is a
sin, and you are being suitably punished.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top