Jump to content

How to use scanf in C.

- - - - -

  • Please log in to reply
22 replies to this topic

#1
twitch

twitch

    Newbie

  • Members
  • PipPip
  • 10 posts
A lot of new C programmers have trouble with scanf(). So I'm going to show you how to implement scanf in C in this tutorial. :)

The main reason beginners have trouble is scanf works like a pointer so you have to point to what you are getting input for

#include<stdio.h>

int main()
{
   int myvariable;

   printf("Enter a number:");
   scanf("%d",&myvariable);
   printf("%d",myvariable);

   return 0;
}



See, when we used scanf we first declared what the variables type was
"%d" for int ,"%f" for float ,"%e" for a scientific notation (1e10) ,"%c" for char , "%s" for strings.

Then in the second part we have to use & just like in a pointer to point to the variable instead of just getting its value.
Remember without & your program will likely crash.

For handling strings with whitespace (sentences) and in files use fgets. Here is one of our tutorials on using it:
Reading And Writing Files In C.

You can bookmark or print the manual page on scanf for later reference: Scanf() - C reference

Do you have a scanf example to share?

Edited by Roger, 23 May 2012 - 03:51 PM.


#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
Actually a nice little tutorial, I like your coding style, it's clean and the layout of the tutorial is too. Good job.

#3
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY
Nice tutorial, but even though I know how to use scanf now, I have no idea what it is used for :confused:

When/Why is scanf() used?

#4
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts

Sidewinder said:

Nice tutorial, but even though I know how to use scanf now, I have no idea what it is used for

When/Why is scanf() used?
You're using scanf() to get userinput in C, like you're using std::cin in C++.

#5
rong889

rong889

    Newbie

  • Members
  • Pip
  • 2 posts
Nice tutorial.:):)

#6
G_Morgan

G_Morgan

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 537 posts
I'll comment on scanf since I think it's an awful function. Scanf expects data of the correct type. If you enter in the wrong data then it fails to work. Now you can catch this by catching the return code, scanf returns the number of items it read in so if it returns 0 you know that it failed on the first entry. You may think this appropriate

int check = 1;

int var = 0;

while(check){

    check = !scanf("%d", &var);

}

Since there's only one variable read, it will either return 0 on failure or 1 on success. The ! inverts this and check feeds it back into the while loop (so that this will loop until there is correct input).

You may think job done. Unfortunately scanf doesn't flush the input buffer on failure so if I enter 'error' it will stay on the input buffer for the next time, this program gives an infinite loop on an error.

So what can we do? We could call fflush(stdin); but this behaviour is undefined according to the C standard. Windows happens to define fflush on stdin but I've seen code elsewhere which doesn't work.

Personally I prefer to use fgets.
char buff[20];

fgets(buff, size, stdin);
and then parse the output. It certainly doesn't leave mess on stdin and is fully portable. Once you've got a set of functions written to do this you won't ever need to touch temperamental scanf again. The one thing to be careful of, fgets leaves the newline character on the end of the output so you will want to write a function that scans it and replaces it with the null character.

#7
boykie

boykie

    Newbie

  • Members
  • Pip
  • 2 posts
Hi,

I'm not sure if this is the right place, but I have a puzzling issue with the following code:

#include <stdio.h>

int main(int argc, char** argv)
{
	int aNumber;
	char aChar;
	
	
	printf("\nEnter a number:");
	scanf("%d", &aNumber);
	printf("\nEnter a character:");
	scanf("%c", &aChar);
	printf("\nHello\n");
	printf("\nThe number entered is %d\n", aNumber);
	printf("\nThe character entered is %c\n", aChar);
	
	return 0;
}

When compiled and run, it only takes input for the first scanf(), aNumber, then just runs to the end without taking input for the second scanf(), aChar.
However, when the code is changed round as:

#include <stdio.h>

int main(int argc, char** argv)
{
	int aNumber;
	char aChar;
	
	printf("\nEnter a character:");
	scanf("%c", &aChar);
	printf("\nEnter a number:");
	scanf("%d", &aNumber);
	printf("\nHello\n");
	printf("\nThe number entered is %d\n", aNumber);
	printf("\nThe character entered is %c\n", aChar);
	
	return 0;
}

It runs as I would expect i.e taking in both aNumber and aChar and displaying them. What is wrong with the first snippet?

#8
Daisycrystal

Daisycrystal

    Newbie

  • Members
  • Pip
  • 7 posts
i inserted a statement
fflush(stdin);
after the first scanf statement of ur 1st code snippet n i workd perfectly
i am an ameteur in c programming
so i dont know how it made difference and why the 2nd program ran perfectly even without the fflush statement.
looking forward for some explaination :-)

#9
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
@boykie:
When reading input with scanf, the input is read after the return key is pressed, but the newline generated by it will not be consumed by scanf. This means the next time you read a char from standard input, the newline will be plugged in instead, thus the skipping.

You can avoid this by using fgets, to read the input as a string then extract what you wish with sscanf. Another way would be to catch the newline completely, with scanf("%c%*c",&achar), %*c will read the newline after the buffer, and rightfully discard it.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#10
rvega

rvega

    Newbie

  • Members
  • Pip
  • 6 posts
does any one know how to go about printing a circle or wheel to the screen (with * or $ or any other character)?

#11
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200

rvega said:

does any one know how to go about printing a circle or wheel to the screen (with * or $ or any other character)?
You will require "for" loops to perform this. Feel free to try something out and post in a new thread if you have any troubles.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#12
boykie

boykie

    Newbie

  • Members
  • Pip
  • 2 posts
@Nullw0rm, thanks for the feedback! I didn't realise the '/0' was saved and used as the next input.

I am however confused as to why it works with the second code snippet?




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users