This question already has answers here:
C Language, scanf issue with char's [duplicate]
(3 answers)
Closed 8 years ago.
I have learnt a few languages in the past and I thought it would be a good I idea to learn C.
I am having a little trouble with scanf...
here is the code:
#include <stdio.h>
#include <string.h>
int main(){
char name[20];
char yn;
printf("Welcome to Benjamin's first C programme! \n\n");
printf("What is your name? \t"); scanf("%s", name); printf("\n");
printf("Is your name %s? [y/n]", name); scanf("%s", yn);
}
I am having trouble with: scanf("%s", yn)
do the following:
printf("Is your name %s? [y/n]", name); scanf("%c", &yn);
What the new scanf does is says "expect a char" and put it in the address of yn
To read into a char use
scanf("%c",&yn);
scanf() can only take pointers as parameters. name is an array so its a pointer by definition, but yn is not. You have to cast it as &yn, a pointer to yn, in order to make scanf() read to it.
Also, yn can only hold a single char, not an array of chars as in name, so you have to tell scanf() you want to read a %c for single char, not a %s for null-terminated string, because if you do you will most likely overwrite the stack and run in trouble.
That being said, use scanf("%c", &yn); instead.
or prepare yourself and do a simple malloc (but that's not the better choice)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char name[20];
char *yn;
yn = (char*) malloc(sizeof(char)*2);
printf("Welcome to Benjamin's first C programme! \n\n");
printf("What is your name? \t"); scanf("%s", name); printf("\n");
printf("Is your name %s? [y/n]", name); scanf("%s", yn);
}
Related
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.
Struggling on my homework assignment.
After I give inputs it stops rather than doing the random array and last print if anyone can help I would appreciate it
#include <stdio.h>
#include <stdlib.h>
int main() {
char name, color;
int age;
int *poer = &age;
char *p = &name;
char *ptr = &color;
printf("What is your name?\n");
scanf(" %s", &name);
printf("How old are you??\n");
scanf(" %d", &age);
printf("What is your favorite color?\n");
scanf(" %s", &color);
char *story[5] = {"old volkswagen beetle", "singlet", "quater", "left sock",
"blackberry bold ninek"};
srand(time(0));
printf("My pal right here %s is %d years old I feel like we have been coding"
" together for a hundred years now I always wonder where the time has gone"
" One thing I have wanted to know is why they love "
"their %s %s so much I guess I might never know\n",
name, age, color, story[rand() % 5]);
return 0;
}
Plenty of errors can be caught by enabling the compiler warnings.
Here is the list of all problems with their proper solutions:
For this line:
srand(time(0));
You need to include the time.h library, otherwise, you will get an implicit definition of time() error message. Passing NULL to time() is a good practice.
As people figured out:
char name, color;
A single char-type cannot hold more than a single ASCII character. Thus, you need to formulate a sequence of characters, called character array. In C99, variable-length arrays are supported. Still, using a macro constant for defining string lengths during compile-time makes the code good. Replace it:
#define MAX_LENGTH 128 // Prefer your length
...
char name[MAX_LENGTH], color[MAX_LENGTH];
In the similar lines:
printf("What is your name?\n");
scanf(" %s", &name);
scanf() function stops reading further input after whitespace. For example, if you input: John Doe, the name will only store John, Doe becomes truncated. Also, never put an ampersand sign for a char-array in scanf().
fgets() is considered safer than this, since it accepts a limited number of characters defined in its second argument. Replace the scanf():
// ... , sizeof name, ... --- is also applicable here
if (fgets(name, MAX_LENGTH, stdin) == NULL) {
// Do something when input's invalid
}
// Input is okay
Note: The fgets() leaves a trailing newline character as soon as it stops receiving user input. To discard this, use this after its usage:
name[strcspn(name, "\n")] = 0;
After applying all these changes, you will not get any further problems.
the following code will be fine
char name[256];
char color[256];
int age;
printf("What is your name?\n");
scanf(" %s", name);
printf("How old are you??\n");
scanf(" %d", &age);
printf("What is your favorite color?\n");
scanf(" %s", color);
in your code, a char was casted to char* the variable will hold data larger than it could. the the stack was ruined
You used char for string which is wrong. You need a char array to store the strings.
Try this:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define STR_MAX 300
int main()
{
char name[STR_MAX];
char color[STR_MAX];
int age;
printf("What is your name?\n");
scanf(" %s", name);
printf("How old are you??\n");
scanf(" %d", &age);
printf("What is your favorite color?\n");
scanf(" %s", color);
char *story[5] = {"old volkswagen beetle","singlet","quater","left sock","blackberry bold ninek"};
srand(time(0));
printf("My pal right here %s is %d years old I feel like we have been coding together for a hundred years now I always wonder where the time has gone One thing I have wanted to know is why they love their %s %s so much I guess I might never know\n",name, age, color, story[rand()%5]);
return 0;
}
your program terminated abnormally because stack was ruined.
char name; //has only 1 byte space
char color; //has only 1 byte space
but these two variables was used to hold data larger than they can. then data was written to some place else which will cause the stack overflow.
code like this will be ok
char name[256];
char color[256];
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.
I have no idea why this code is not working. Could someone please help me? (I want a simple version-fix if it's possible, because I've only started to study C a couple of weeks ago.)
#include <stdio.h>
#include <string.h>
int main ()
{
char *name="alina";
char *input;
printf ("what's your name? \n");
scanf ("%s",&input);
if (input=="alina")
printf("your name is %s good job!\n ",&name);
if (input!="alina")
printf("are you sure? open the program again and insert the correct name");
while (1);
}
you need to apply following changes:
char input[256];
scanf("%s", input);
printf("your name is %s good job!\n ", name);
to compare strings use strcmp - have a look at documentation of this function.
be careful with scanf - think about how long string you can store there and what can go wrong. Have a look at scanf_s
You did some errors. First, if you want to insert a string, you can use the %s, but you have to use an array of char in which you can store that string. That's, you have to write something like this.
char input[100];
scanf("%s", input);
and then it'll work. This snippet of code means: I need to insert (store) a string. So first I create a place in which I can store it (pay attention that the string must be maximum of 99 characters; my array has size 100, but the last character is used to represent the end of the string), and then I use the scanf to write what I want.
The second error is that if you want to compare two strings, you can't simply use the == or !=, like when you do with numbers. The string.h library lets you use the strcmp function, like this:
if (strcmp(name, input) == 0) // this means the strings are equal
...
else
...
remembering that
char* name = "Alina";
char input[100];
Eventually, here you're an inspected version of your code:
#include <stdio.h>
#include <string.h>
int main() {
char* name = "Alina";
char input[100];
printf("What's your name?\n");
scanf("%s", input);
if (strcmp(name, input) == 0)
printf("Your name is %s good job!\n", name);
else
printf("Are you sure? Open the program again and insert the correct name\n");
return 0;
}
The while(1) at the end of your code is absolutely dangerous, because it starts an infinite loop that never ends, crashing your program. You want to definitely remove it!
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
I am using c to create a very basic programme. I using scanf to get input from the console but when I use it with a char it just seems to 'skip' it.
Here is the code:
#include <stdio.h>
#include <string.h>
int main(){
char name[20];
char yn;
printf("Welcome to Benjamin's first C programme! \n\n");
do{
printf("What is your name? \t");
scanf("%s", name);
printf("\n");
printf("Is your name %s [y/n]?", name);
scanf("%c", &yn);
printf("\n");
} while(yn != 'y');
}
Add space at the begining of the string format in the second scanf()
scanf(" %c", &yn);
This space will catch the newline that you type after the first input
Your apparent skipping is because %s specifier matches a string of characters, until a whitespace or a newline character. In this case, it is a newline. The problem is that it leaves it in the input stream, and the next reading matches it. So, in your yn variable, there will always be the newline character. In order to prevent this, insert a space before %c specifier, to skill all blanks (whitespace, newline, tab):
scanf(" %c", &yn);
Also note that for the same reason, your program will not work if I insert my full name (i.e. I insert spaces).
As an alternative, try using getchar()
Replace:
scanf("%c", &yn);
With:
getchar();//eat the '\n' from <return>
yn = getchar();
For the record I like the other answers better, just offering this as an alternative...