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.
|
|
0
|
|
|
|
Reply
|
haihua79 (7)
|
2/8/2006 4:09:09 PM |
|
obdict wrote:
> 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
|
|
0
|
|
|
|
Reply
|
robert.f.harris (386)
|
2/8/2006 4:33:35 PM
|
|
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?
|
|
0
|
|
|
|
Reply
|
haihua79 (7)
|
2/8/2006 4:39:07 PM
|
|
On 2006-02-08, obdict <haihua79@gmail.com> wrote:
> 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.
> 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.
|
|
0
|
|
|
|
Reply
|
random832 (841)
|
2/8/2006 4:42:04 PM
|
|
obdict wrote:
> 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)
|
|
0
|
|
|
|
Reply
|
Lew.Pitcher2 (80)
|
2/8/2006 4:45:39 PM
|
|
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
|
|
0
|
|
|
|
Reply
|
haihua79 (7)
|
2/8/2006 4:45:48 PM
|
|
On 2006-02-08, obdict <haihua79@gmail.com> wrote:
> 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.
|
|
0
|
|
|
|
Reply
|
random832 (841)
|
2/8/2006 4:48:55 PM
|
|
obdict wrote:
> 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
>
> But on a different machine (Fedora Core Test 3), I got different
> results (negative
> integer) for different input (random character strings).
>
> Thanks
>
|
|
0
|
|
|
|
Reply
|
robert.f.harris (386)
|
2/8/2006 5:03:17 PM
|
|
"obdict" <haihua79@gmail.com> wrote in message
news:1139414949.436348.188620@g14g2000cwa.googlegroups.com...
> 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
|
|
0
|
|
|
|
Reply
|
mkwahler (3821)
|
2/8/2006 5:33:47 PM
|
|
I got it. Thanks to all you folks!
|
|
0
|
|
|
|
Reply
|
haihua79 (7)
|
2/8/2006 5:50:24 PM
|
|
obdict wrote:
> 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)
|
|
0
|
|
|
|
Reply
|
Lew.Pitcher2 (80)
|
2/8/2006 6:36:15 PM
|
|
obdict wrote:
>
> 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/>
|
|
0
|
|
|
|
Reply
|
cbfalconer (19183)
|
2/8/2006 7:59:59 PM
|
|
On 8 Feb 2006 09:50:24 -0800, in comp.lang.c , "obdict"
<haihua79@gmail.com> wrote:
>I got it. Thanks to all you folks!
Could you please also get this:
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header. For more information, please go here
<http://cfaj.freeshell.org/google/>
----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
|
|
0
|
|
|
|
Reply
|
markmcintyre (4547)
|
2/8/2006 11:39:47 PM
|
|
|
12 Replies
23 Views
(page loaded in 0.168 seconds)
Similiar Articles: converting a character string into a variable name - comp.lang ...I want to store the names of these variables in character strings to be used in the routine that ... How to convert bytearray into integer? - comp.lang.python ... display integer in MessageBox - comp.lang.c++.moderatedUnfortunatedly I'm new in C++ and I don't know > variable types like LPCWSTR ... in a messagebox: messagebox, integer I want to know how to turn an integer into character to ... PL1 CHAR limit is 32767, but I need more long string type - comp ...X...S T A R T if we store into a char(32000 ... Long integer to bytes? - comp.lang.java.help PL1 CHAR limit is 32767, but I need more long string ... String to std_logic_vector - comp.lang.vhdl... or something to push my revision number into a ... std::runtime_error which are required to store ... Tim: time; variable Int: integer; variable cha: character; variable str ... Converting character to float. - comp.lang.fortranThe problem is how to I convert each of the expense values into a ... on all C++ compilers. Example how to use sprintf to convert integer and float variables to character ... Evaluate character macro variable - comp.soft-sys.sasHi, I would like to know how to evaluate a macro variable and store it into another ... and the %eval only works with numerics, What turns your variables in to character ... how to assign a NaN? - comp.lang.fortran... good way to be a ble to assign NaN to integer, real and character ... use double precision real instead of integer variables ... One could argue that systems that store, say ... help with convert real value to character - comp.lang.fortran ...outfile=out_path // damp // '_outfile_name.txt' The real value of the 'damp' variable has to be converted to a character to insert into the output file name. char to string - comp.soft-sys.matlabconverting a character string into a variable name - comp.lang ... I ... problems is: I want to write several variables, arrays and scalars, out to a file. I want to store ... How to change length of a num column - comp.soft-sys.sas ...... sql; create table dept(deptno num(20), dname char ... On a Windows platform, the largest integer that can ... variable affects only the space used to store the variables on ... Concatenate string variables into value labels for a numeric ...It makes the values of a string variable into value labels ... Need to concatenate numeric values into one char value - comp.soft ... Concatenate string variables into ... creating a counting variable - comp.soft-sys.sasThen the new data set cretade in the work file has ... Hi, I have a character ... ... rows. - comp.soft-sys.sas Hi. ... in a CSV file and place the values into integer variables ... Converting a cell array into a dataset - comp.soft-sys.matlab ...... this behavior was introduced by design, I would think that the integer ... array into a dataset - comp.soft-sys.matlab ... converting a character string into a variable ... converting double to long - comp.lang.c... need to have the mantissa part 151177 to a long variable i ... long convert(double value) { char value_str[124 ... Another modf (this time for the integer part) and a ... External variables - comp.lang.asm.x86Yes, my_data is an ARRAY of 32 8-bit character ... If you put the address of something in a variable type designed to store ... You may have been confused into thinking I ... Store a char into an integer variable - C / C++Store a char into an integer variable. C / C++ Forums on Bytes. C++:How do i store a char array as a int variable? - Yahoo! Answershow can i store whats in that char array into a int variable? OR how can i extract that 123 from that text file and directly store it into a int variable? 7/7/2012 1:00:07 PM
|