473,385 Members | 1,752 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Store a char into an integer variable

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.

Feb 8 '06 #1
12 8414
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
Feb 8 '06 #2
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?

Feb 8 '06 #3
On 2006-02-08, obdict <ha******@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.

Feb 8 '06 #4
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

Feb 8 '06 #5
On 2006-02-08, obdict <ha******@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.
Feb 8 '06 #6
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)
Feb 8 '06 #7
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

Feb 8 '06 #8
"obdict" <ha******@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.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
Feb 8 '06 #9
I got it. Thanks to all you folks!

Feb 8 '06 #10
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)
Feb 8 '06 #11
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/>

Feb 8 '06 #12
On 8 Feb 2006 09:50:24 -0800, in comp.lang.c , "obdict"
<ha******@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 =----
Feb 8 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Sanjay | last post by:
hi, We are currently porting our project from VB6 to VB .NET. Earlier we used to make scale transformations on objects like pictureBox , forms etc.Now Such transformations are made on the...
23
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
5
by: IamZadok | last post by:
Hi I was wondering if anyone knew how to convert a string or an integer into a Static Char. Thx
9
by: Juggernaut | last post by:
I am trying to create a p_thread pthread_create(&threads, &attr, Teste, (void *)var); where var is a char variable. But this doesnt't work, I get this message: test.c:58: warning: cast to pointer...
5
by: Roy Gourgi | last post by:
Hi, I am used to working in Visual FoxPro and I would like to be able to create a database and store and retrieve information from it. What is the simplest way to do it and what should I be...
4
by: Rob | last post by:
Using VB.net and SQL server... I have a stored procedure that is simply returning a row count.... I know how to execute a stored procedure and add the output parameter. But how do I store...
18
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
33
by: Prasad | last post by:
Hi, Can anyone please tell me how to store a 13 digit number in C language ? Also what is the format specifier to be used to access this variable ? Thanks in advance, Prasad P
0
by: harshad | last post by:
Dear All,Here I am facing problem to store image.I am trying to store byte array(image) in to session variable so at time of update I will got that byte array and I do my update. here i am given...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.