Segmentation fault when handling characters - c

Fair warning, I am quite new to C, and am still very much a beginner with the language. This problem has stuck with me for a while and I thought someone here might be able to help.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old \n", age);
double gpa;
printf("Enter your GPA: ");
scanf("%lf", &gpa);
printf("You're GPA is %lf \n", gpa);
char name[20];
printf("Please enter your name: ");
scanf("%s", &name);
printf("Your name is %s \n", name);
char grade;
printf("Enter your grade: ");
scanf("%s", &grade);
printf("Your grade it %s \n ", grade);
return 0;
}
The problem lies in the 'grade' section, everything else works perfectly.
The output of the program with user input is
Enter your age: 3
You are 3 years old
Enter your GPA: 4.5
You're GPA is 4.500000
Please enter your name: Test
Your name is Test
Enter your grade: B
Segmentation fault (core dumped)
Hopefully someone here can help. All the best!

Input for getting the input of grade would be
scanf(" %c",&grade);
The issue arises because the grade is a char variable, not a char array.
char -> %c
char array(aka String in C) -> %s

The reason you get segmentation fault is that you are scanning the input B as a string instead of a character (it is equivalent to {'B','\0'}, so it is not just B) and you are trying to assign this string into a char .
If you want to get a character as input (seems like you want it this way) you must do :
scanf ("%c",&grade);
The %c format specifier is for scanning chars, and &grade is basically the address of grade.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
However, if you want to get a string as input (i.e. character array in C) , you must define grade like this :
char grade [n];
(n is a number telling the size of array)
and the scanf line must be :
scanf ("%s",grade);
The %s format specifier is for getting strings (i.e. character arrays in C). The reason why we used grade without an address-of (&) operator is related with pointers. Because grade is already a pointer; we need its value (i.e. the address of the first character of array), not address. Check this link for better understanding. Also check this post after ensuring you've understood the logic of pointers.
Note : This is a self study question. Avoid getting downvoted as possible.

Related

i am getting a unknown error in my c program

Code:
#include <stdio.h>
void main()
{
int s1,s2,s3,s4,s5,sum;
float per;
printf("Enter subject 1 marks out of 100 \n");
scanf("%d",s1);
printf("Enter subject 2 marks out of 100\n");
scanf("%d",s2);
printf("Enter subject 3 marks out of 100 \n");
scanf("%d",s3);
printf("Enter subject 4 marks out of 100\n");
scanf("%d",s4);
printf("Enter subject 5 marks out of 100\n");
scanf("%d",s5);
sum=s1+s2+s3+s4+s5;
per=sum/100;
if (per>60 && per<70){
printf("your percentage is %d and you get 10% schoolarship",per)
;}
else if (per>70.1 && per<90){
printf("your percentage is %d and you get 20% schoolarship",per)
;}
else {
printf("your percentage is %d and you get 30% schoolarship",per)
;}
}
Output:
I am trying to make a percentage calculator and it shows a weird output.
What am I doing wrong?
When you call scanf, it is important to pass in the address of the variable you want to store. Otherwise, scanf will not behave as you expect.
Right now, you are not passing in the address to scanf; but rather the variable itself.
So you should do something like:
scanf("%d",&s1);
instead.
https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
I recommend reading a little bit about how scanf works at the following link.
"Following is the declaration for scanf() function.
int scanf(const char *format, ...)"
Additionally, check out this link for a few examples of scanf:
https://www.programiz.com/c-programming/c-input-output
scanf("%d", &testInteger);
The syntax is format first, then pass in the address of where you want to store the data.
scanf() requires a pointer to the value, it should be scanf("%d",&s1);

Errors about scanf and printf expected types

My issue is coming from the %c name input, I am getting an error that it is expecting type char * but has type char * [15] for the scanf function. I am also getting an error in the printf where the %c expects int but has type char *. I am still quite new at this so if it could be explained as simply as possible that would be amazing.
#include <stdio.h>
struct Student {
int StudentID;
char Name[15];
float Mark1;
float Mark2;
float Mark3;
} a;
int main() {
float ave;
printf("Please input Student's ID \n");
scanf("%d", &a.StudentID);
printf("Please input Student's name. \n");
scanf(" %c", &a.Name);
printf("Input Mark 1. \n");
scanf("%f", &a.Mark1);
printf("Input Mark 2. \n");
scanf("%f", &a.Mark2);
printf("Input Mark 3. \n");
scanf("%f", &a.Mark3);
ave = (a.Mark1 + a.Mark2 + a.Mark3) / 3;
printf("Student Detail\nStudent ID: %d\nName: %c\nMark 1: %.2f\n Mark 2: %.2f\n Mark 3: %.2f\nAverage: %.2f\n",
a.StudentID, a.Name, a.Mark1, a.Mark2, a.Mark3, ave);
return 0;
}
Your problem is related to the difference between an array of chars and a single char.
The %c format only reads in one character at a time.
If you wish to read a string of characters use %s and it will read until a whitespace. (Please make sure you don't try to read a name more than 14 characters long into your 15 character buffer)
In more depth, your char Name[15] is actually a pointer to a series of chars in memory. You are accidentally trying to change to pointer itself, instead of the chars that it points to. This is why the compiler expects a char * .
Instead if you truly meant to only read one char you could use
scanf(" %c", &a.Name[0]);
to place the character in the first block of the Name array.
If this is too complicated don't worry, it will all come eventually :)
For now I think %s will suffice.
You can use %14s to be extra safe.
Also don't forget to use %s in the final printf as well
In your scanf() call, %c tells scanf() to accept a single character. But your argument is a character array. C is a low-level language; it's not smart enough to realize you wanted a string (char array) as input. You have to tell it by using %s instead of %c.

C : when asking for 2 inputs from a user the 2nd question will not prompt an input to be stored in a variable

If I try grade or fullname one at a time I will get the expected result
"Enter your Grade: "
"Your grade is x"
"Enter your full name:"
"Your full name is xxxx xxxx"
If I run below the print out is
Enter your Grade:2
Your grade is 2
Enter your full name: Your full name is
I can't figure out why I am not been prompted for a second input especially as I know it works when tried on its own */
int main()
{
char grade;
printf("Enter your Grade: ");
scanf("%c", &grade);
printf("Your grade is %c \n", grade);
char fullName[20];
printf("Enter your full name: ");
fgets(fullName, 20, stdin); /*2nd argument specify limits of inputs*, 3rd means standard input ie command console */
printf("Your full name is %s \n", fullName);
return 0;
}
scanf("%c"); buffer problem, %c will only eat one character, so or \n will stay in the buffer for the next one to read.
Try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
char grade;
printf("Enter your Grade: ");
scanf("%c", &grade);
getchar(); // here
printf("Your grade is %c \n", grade);
char fullName[20];
printf("Enter your full name: ");
fgets(fullName, 20, stdin); /*2nd argument specify limits of inputs*, 3rd means standard input ie command console */
printf("Your full name is %s \n", fullName);
return 0;
}
use getchar(); to eat the extra character in the buffer.
Don't mix scanf() with fgets() - in this case, the newline present in the buffer, left untouched by scanf() will be fed to fget() and it won't "ask" for any new input.
Better to use fgets() in all the user-inputs.
The problem lies in this line scanf("%c", &grade); Whenever you use scanf() always keep in mind that the enter key will be stored in your buffer. Since enter key was in your buffer, it went right into fullName when fgets(fullName, 20, stdin); is executed. That's way you got your output:
Enter your Grade:2
Your grade is 2
Enter your full name: Your full name is
You can solve the problem by using getchar(); or getch(); right after scanf(); to capture the Enter key and ensures that fullName get the correct input. Another way to solve it is to use fflush(stdin);. They basically do the same thing, but fflush(stdin); clear Enter key from the buffer. Therefore, fflush(stdin); should be used after scanf(); to clear the unwanted Enter key left by scanf();
This is a long one and have a lot to take in, but I hope this information helps :)))

C program not taking user input [duplicate]

This question already has answers here:
How to do scanf for single char in C [duplicate]
(11 answers)
The program doesn't stop on scanf("%c", &ch) line, why? [duplicate]
(2 answers)
Closed 2 years ago.
i am a beginner in C programming. I was learning about the user inputs. The following piece of code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char grade;
printf("Enter you grade: ");
scanf("%c", &grade);
printf("Your grade is %c.", grade);
return 0;
}
does what I intend it to do i.e.
ask for the grade
display the grade
But when I modify the code to the following :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age;
printf("Enter you age: ");
scanf("%d", &age);
printf("You are %d years old.\n", age);
printf("-----------------------------\n");
double gpa;
printf("Enter your GPA: ");
scanf("%lf", &gpa);
printf("Your GPA is %f. \n", gpa);
printf("-----------------------------\n");
char grade;
printf("Enter you grade: ");
scanf("%c", &grade);
printf("Your grade is %c.", grade);
return 0;
}
it does the following:
asks for the age
displays the age
asks for the gpa
displays gpa
asks for grade
it doesnt display grade.
The output looks like:
Enter you age: 45
You are 45 years old.
-----------------------------
Enter your GPA: 4
Your GPA is 4.000000.
-----------------------------
Enter you grade: Your grade is
.
please suggest me what I am doing wrong.
When you enter your age, this is what is in the input buffer just before the scanf(%d) starts retrieving characters:
45<newline>
The scan(%d) skips any white space in the buffer (there isn't any), reads the 45, but leaves the newline. Then when you enter your GPA, this is what is in the input buffer just before the scanf(%lf) starts retrieving characters:
<newline>4<newline>
The scan(%lf) skips any white space in the buffer (the newline), reads the 4, but again leaves the newline. In other words, the leading newline doesn't matter if your next next scanf also skips whitespace such as moving from the first entry to the second.
But scanf(%c) does not skip white space. It simply reads the next character, which is a newline:
<newline>A<newline>
That's why tour period appears on the following line, it has read a character, but that character was the newline rather than the grade.
Section 7.21.6.2 The fscanf function, in the ISO C11 standard, has this to say on the first step of processing a conversion specifier (my emphasis):
Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.
A quick fix would be to manually skip whitespace yourself, something like:
printf("Enter your grade: ");
scanf(" %c", &grade);
printf("Your grade is %c.", grade);
as per that same section of the standard:
A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

scanf_s reading characters what am i doing wrong?

{
printf("Please give a random positive number for X: \n");
scanf_s("%i", &X);
char ch = getchar();
char Gender;
if (isdigit)
{
printf("Hay um... sorry what my i call you?");
scanf_s("%i", Gender);
printf("%lf \n" Gender ", if you may, please reread what i said, i asked you to give me a RANDOM NUMBER. \ncan you please explain to me why you gave me out of 1 through infinite numbers, a random letter? \n \n ");
};
my problem is with ["%lf \n" Gender] saying that its expecting a [ ) ] can someone please explain what i am doing wrong?
A few issues here:
scanf_s takes a pointer to where you want to store the read value, so it should be scanf_s("%i", &Gender);
In C, you can't just insert a char into a string. I'm not sure exactly what you want from this, since %lf is a really weird format for printing a char, but that's what I'm assuming you want. In that case, you would want to move Gender to the end: printf("%lf \n...letter? \n \n", Gender);. This will insert Gender in the position of %lf.

Resources