The problem is the following two lines:
printf("\n\nEnter Your Name: ");
scanf("%c", &usrname);
You are telling the user to enter something that consists of more than a single character, but you are only extracting a single character from the input stream and writing it to usrname
.
For example, if you enter Michael
, then you will extract the M
from the input stream, leaving ichael
on the stream.
Afterwards, you will execute the line
scanf("%d", &age);
which will attempt to convert what is left on the input stream to an integer. However, this will fail, because it is not possible to convert ichael
to an integer.
It is generally not recommended to use scanf
for line-based user input. This is because scanf
does not behave in an intuitive manner. For example, as demonstrated above, it does not always read one line of input in one function call, which can cause trouble, as it did with you.
For this reason, it is generally recommended to use the function fgets
instead, which will always read exactly one line of input, if possible. After reading one line of input as a string, you can attempt to convert it to an integer, for example using the function strtol
.
Note that fgets
will also write the newline character at the end of the line to the string, so you will probably want to remove it. You may want to read this question on how to do that:
Removing trailing newline character from fgets() input
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char usrname[200];
char line[200];
int age;
printf("Hello, Welcome to the birth year calculator!");
printf("\n\nEnter Your Name: ");
fgets( usrname, sizeof usrname, stdin );
//remove newline character
usrname[strcspn(usrname,"\n")] = '\0';
printf("Enter your age at the end of this year: ");
fgets( line, sizeof line, stdin );
age = strtol( line, NULL, 10 );
return 0;
}