Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can scanf() store values?

Tags:

c

scanf

Hi I am now learning the C language and I have a little problem with a exercise of the book I read. My code is this:

#include<stdio.h>
int main()
{
  unsigned char one=0;
  unsigned char two=0;
  printf("Quantity 1 = ");
  scanf("%d",&one);
  printf("Quantity 2 = ");
  scanf("%d",&two);
  printf("The value is %d",one);
  return 0;
}

Why when I am trying to see the value of one the initial value appears and not the value after the scanf?

like image 526
paulakis Avatar asked Aug 21 '13 18:08

paulakis


3 Answers

You need to use int type in conjuction with %d specifier, and char with %c specifier. And %u with unsigned integers.

#include<stdio.h>
int main()
{
    unsigned int one=0; unsigned int two=0;
    printf("Quantity 1 = ");scanf("%u",&one);
    printf("Quantity 2 = ");scanf("%u",&two);
    printf("The value is %u",one);
    return 0;
}

Basicaly, scanf will try to read integer from input and it will try to store it inside memory location that is not large enough, so you will have undefined behavior.

You can find good reference here.

However, if you try to use character for an input type, you may want ask yourself why you won't get a chance to enter a second Quantity (if you type 4 and press enter). This is because second scanf will read enter key as a character. Also, if you try to type 21 (for a twentyone), it will fill the first value with 2 and second with 1 (well, with their ASCII values).

So, be careful - be sure that you always choose the right type for your variables.

like image 63
Nemanja Boric Avatar answered Oct 15 '22 04:10

Nemanja Boric


Never use scanf. Never use scanf. Seriously, never use scanf.

Use fgets (or getline, if you have it) to read an entire line of input from the user, then convert strings to numbers with strtol or its relatives strtod and strtoul. strsep may also be useful.

like image 20
zwol Avatar answered Oct 15 '22 06:10

zwol


Check if scanf() is working properly by reading its return value. For quickstart, read the details about scanf() at this link.

What you are doing is inputting a integer using "%d" into an unsigned char variable, therefore scanf() may not be working as it should.

like image 41
Don't You Worry Child Avatar answered Oct 15 '22 04:10

Don't You Worry Child