Jump to content




Recent Status Updates

  • Photo
      18 Aug
    KodeKool

    When faced with a wall of errors and no hope to fix them, remember the following "Programs always do what you tell them to, and seldom what you want them to, but eventually you'll run out of things that can go wrong and it'll just work. and that's the secret to good programming."

    Show comments (2)
View All Updates

Developed by Kemal Taskin
Photo
* * * * * 2 votes

How to use scanf in C.

myvariable scanf

  • Please log in to reply
30 replies to this topic

#1 twitch

twitch

    CC Newcomer

  • Just Joined
  • PipPip
  • 10 posts

Posted 09 June 2007 - 08:45 PM

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. smile.png

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

 

If you are interested in finding out more, we also have tutorials on sscanf and printf (Part 1 and Part 2).


Do you have a scanf example to share?


Edited by Roger, 24 February 2013 - 09:43 PM.
added links

  • 1

#2 v0id

v0id

    Retired

  • Retired Mod
  • PipPipPipPipPipPipPipPip
  • 2,313 posts

Posted 09 June 2007 - 10:34 PM

Actually a nice little tutorial, I like your coding style, it's clean and the layout of the tutorial is too. Good job.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#3 John

John

    CC Mentor

  • Moderator
  • 4,450 posts
  • Location:New York, NY

Posted 10 June 2007 - 04:47 AM

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?
  • 0

#4 v0id

v0id

    Retired

  • Retired Mod
  • PipPipPipPipPipPipPipPip
  • 2,313 posts

Posted 10 June 2007 - 06:16 AM

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++.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#5 rong889

rong889

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 10 June 2007 - 07:08 AM

Nice tutorial.:):)
  • 0

#6 G_Morgan

G_Morgan

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 442 posts

Posted 16 October 2007 - 07:55 AM

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.

Edited by Roger, 31 January 2013 - 11:04 AM.

  • 0

#7 boykie

boykie

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 15 September 2010 - 12:49 PM

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?
  • 0

#8 Daisycrystal

Daisycrystal

    CC Lurker

  • New Member
  • Pip
  • 7 posts

Posted 18 September 2010 - 09:17 PM

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 :-)
  • 0

#9 Alexander

Alexander

    I do have 9 lives, you know.

  • Moderator
  • 3,871 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 18 September 2010 - 10:50 PM

@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.
  • 0
Be sure to check out the new site additions - brought to you by your friendly CODECALL staff-person.
If a suggested code/method fails, informing us is less important than telling us why or what errors had occurred.

#10 rvega

rvega

    CC Lurker

  • Just Joined
  • Pip
  • 6 posts

Posted 11 October 2010 - 04:11 PM

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

#11 Alexander

Alexander

    I do have 9 lives, you know.

  • Moderator
  • 3,871 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 11 October 2010 - 07:09 PM

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.
  • 0
Be sure to check out the new site additions - brought to you by your friendly CODECALL staff-person.
If a suggested code/method fails, informing us is less important than telling us why or what errors had occurred.

#12 boykie

boykie

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 30 October 2010 - 08:18 AM

@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?
  • 0





Also tagged with one or more of these keywords: myvariable, scanf