why the space included in string doesn't work? - c

#include <stdio.h>
#include <stdlib.h>
int main()
{
char firstname[15];
char lastname[15];
char crush_first[15];
char crush_last[15];
int babies;
printf("What is your first name?\n");
scanf("%s", firstname );
printf("What is your last name?\n");
scanf(" %s", lastname);
/* see i have added space before the character conversion but on exectution
of this file no space is in between the two strings*/
printf("What is your crush's first name?\n");
scanf("%s", crush_first );
printf("What is your crush's last name?\n");
scanf(" %s", crush_last );
printf("How many kids will you have?");
scanf("%d", &babies );
printf("%s%s will have a lovely marriage with %s%s and they will have %d kids",firstname,lastname,crush_first,crush_last,babies);
}
now here i want to do is to add space by default in the string. "__etc" i want the string to also store these values . Though i have added space before %s repeatedly but it is not recognizing.

From scanf doc:
s matches a sequence of non-whitespace characters (a string) [...]
Also if someone enters string longer then your receive buffer, you will overflow the buffer.
Maybe use fgets if you want to read the line up until a newline:
fgets(lastname, sizeof(lastname), stdin);

Related

Function execution not waiting in do-while loop [duplicate]

I tried this code below, but it seems scanf("%c") is skipped. It only asks me to enter name and age and skips the lines below that. It just print the text in the printf above the if statements. Can anyone help?
#include<stdio.h>
int main()
{
int age;
char sex;
char name[20];
char status;
printf("Enter your last name\n");
scanf("%s", &name);
printf("Enter your age\n");
scanf("%d", &age);
printf("Enter sex (M/F)\n");
scanf("%c", &sex);
printf("your status,married, single,irrelevant (M/S/I)\n");
scanf("%c", &status);
if(age>=16 && sex=='M')
printf("hello, Mr %s\n", name);
if(age<16 && sex =='M')
printf("hello, Master %s\n", name);
if(sex=='F' && status=='M')
printf("hello, Mrs %s\n", name);
if(sex=='F' &&(status=='S' ||status=='I'))
printf("hello,miss %s\n", name);
}
Change
scanf("%c", &sex);
to
scanf(" %c", &sex);
^
space
and
scanf("%c", &status);
to
scanf(" %c", &status);
^
space
The problem is because of trailing newline characters after your second call to scanf(). Since it is of %d type specifier, when you press Enter A newline character ( '\n' ) is left in the stream and the next scanf() tries to read that newline character, and thus, it seems as though it just skipped input, but in fact, it read the newline character.
So, the newline character is stored in the variable sex, and thus, it skips asking you for input for that variable.
Unless you are interested in whitespace like newlines, do not use %c. Simply use the string conversion %s and use the first character of the input.
Rationale: All scanf conversion specifiers except %c ignore white space including newlines. They are designed to read sequences of input tokens (numbers, words) where the amount and nature of white space is irrelevant. The words can all be on the same line, or each word on a different line; scanf wouldn't care unless you force single character reads with %c which is almost never necessary.
Change your code to
#include<stdio.h>
int main()
{
int age;
char sex;
char name[20];
char status;
printf("Enter your last name\n");
// scanf("%s", &name);
fgets(name,20,stdin);
printf("Enter your age\n");
scanf("%d", &age);
printf("Enter sex (M/F)\n");
scanf(" %c", &sex);
printf("your status,married, single,irrelevant (M/S/I)\n");
scanf(" %c", &status);
if(age>=16 && sex=='M')
printf("hello, Mr %s\n", name);
if(age<16 && sex =='M')
printf("hello, Master %s\n", name);
if(sex=='F' && status=='M')
printf("hello, Mrs %s\n", name);
if(sex=='F' &&(status=='S' ||status=='I'))
printf("hello,miss %s\n", name);
return 0;
}
Here, I have added an extra space before the format specifier %c, to accommodate any previous input like newline (\n). Another alternative method is to use getchar() immediately before you take any character input.
Also, if you perform string input with scanf, it will not read the input after encountering a whitespace. So, instead use fgets for taking any string input which might contain spaces.
Another thing I changed in your code (trivial) is int main() and return 0.
This happens because blankspace is also treated as a character and and happens when you press enter.
So Leave a space.
scanf(" %c",&something);
You can do the following for all scanfs.
scanf("%c\n",&smth);
And then enter the values one by one separating them by newlines (press Enter).
This helped me too when I had the same problem.
scanf("%c*",&smth);
That makes scanf skip any other characters that a user might input, including newlines.
Note: use appropriate format strings for each type (%s for strings, %d for integers, etc).

Printing an int value obtained from user

The problem is at the age part, the compiler does not give me any errors but when I run it it prints a random number for int age
printf("Enter your name:");
scanf(" %s",&name1);
int age;
printf("\n\nHow old are you?");
scanf(" %d",&age);
char gender;
printf("\n\nEnter your gender[Male/Female]:");
scanf(" %s",&gender);
char confirmation;
printf("Confirmation: Your name is %s , you are %d years old , and you are a %s.\n\nAnswer[Y/N]:",&name1,age,&gender);
Here is your problem.
char gender;
scanf(" %s",&gender);
gender is a char. That is, it only has memory for a 1 byte character. But you are using it as a string. You probably have the same problem for name1 since you are using & for that as well but can't be sure as you don't show that.
Change that to be something like:
char gender[8] // Enough to fit "Female" and terminating NULL
scanf("%7s", gender);
Extra note: scanf is a bit awkward to use to prevent buffer safety. May consider something like fgets with sscanf instead.
There is also dynamic allocation, where you now do not have to specify the amount of storage to use. Using the length modifier %m with the string type modifier s:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *name = NULL
char *gender = NULL;
int age;
printf("Enter your name: ");
scanf("%ms", &name);
printf("\nHow old are you? ");
scanf("%d", &age);
printf("\nEnter gender: ");
scanf(" %ms", &gender);
printf("\n%s %d %s\n", name, age, gender);
free(name); // free the memory
free(gender); //
return 0;
}
In the last couple of lines you will notice a several calls to free. This is because you are left with the responsiblility to free the memory allocated by scanf.
As pointed out by #Matt McNabb if you are on a non-posix compliant system, this will not work. You can use a in place of m, while including #define _GNU_SOURCE on the first line.

scanf("%c") call seems to be skipped

I tried this code below, but it seems scanf("%c") is skipped. It only asks me to enter name and age and skips the lines below that. It just print the text in the printf above the if statements. Can anyone help?
#include<stdio.h>
int main()
{
int age;
char sex;
char name[20];
char status;
printf("Enter your last name\n");
scanf("%s", &name);
printf("Enter your age\n");
scanf("%d", &age);
printf("Enter sex (M/F)\n");
scanf("%c", &sex);
printf("your status,married, single,irrelevant (M/S/I)\n");
scanf("%c", &status);
if(age>=16 && sex=='M')
printf("hello, Mr %s\n", name);
if(age<16 && sex =='M')
printf("hello, Master %s\n", name);
if(sex=='F' && status=='M')
printf("hello, Mrs %s\n", name);
if(sex=='F' &&(status=='S' ||status=='I'))
printf("hello,miss %s\n", name);
}
Change
scanf("%c", &sex);
to
scanf(" %c", &sex);
^
space
and
scanf("%c", &status);
to
scanf(" %c", &status);
^
space
The problem is because of trailing newline characters after your second call to scanf(). Since it is of %d type specifier, when you press Enter A newline character ( '\n' ) is left in the stream and the next scanf() tries to read that newline character, and thus, it seems as though it just skipped input, but in fact, it read the newline character.
So, the newline character is stored in the variable sex, and thus, it skips asking you for input for that variable.
Unless you are interested in whitespace like newlines, do not use %c. Simply use the string conversion %s and use the first character of the input.
Rationale: All scanf conversion specifiers except %c ignore white space including newlines. They are designed to read sequences of input tokens (numbers, words) where the amount and nature of white space is irrelevant. The words can all be on the same line, or each word on a different line; scanf wouldn't care unless you force single character reads with %c which is almost never necessary.
Change your code to
#include<stdio.h>
int main()
{
int age;
char sex;
char name[20];
char status;
printf("Enter your last name\n");
// scanf("%s", &name);
fgets(name,20,stdin);
printf("Enter your age\n");
scanf("%d", &age);
printf("Enter sex (M/F)\n");
scanf(" %c", &sex);
printf("your status,married, single,irrelevant (M/S/I)\n");
scanf(" %c", &status);
if(age>=16 && sex=='M')
printf("hello, Mr %s\n", name);
if(age<16 && sex =='M')
printf("hello, Master %s\n", name);
if(sex=='F' && status=='M')
printf("hello, Mrs %s\n", name);
if(sex=='F' &&(status=='S' ||status=='I'))
printf("hello,miss %s\n", name);
return 0;
}
Here, I have added an extra space before the format specifier %c, to accommodate any previous input like newline (\n). Another alternative method is to use getchar() immediately before you take any character input.
Also, if you perform string input with scanf, it will not read the input after encountering a whitespace. So, instead use fgets for taking any string input which might contain spaces.
Another thing I changed in your code (trivial) is int main() and return 0.
This happens because blankspace is also treated as a character and and happens when you press enter.
So Leave a space.
scanf(" %c",&something);
You can do the following for all scanfs.
scanf("%c\n",&smth);
And then enter the values one by one separating them by newlines (press Enter).
This helped me too when I had the same problem.
scanf("%c*",&smth);
That makes scanf skip any other characters that a user might input, including newlines.
Note: use appropriate format strings for each type (%s for strings, %d for integers, etc).

Get text from user input using C

I am just learning C and making a basic "hello, NAME" program. I have got it working to read the user's input but it is output as numbers and not what they enter?
What am I doing wrong?
#include <stdio.h>
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%d", &name);
printf("Hi there, %d", name);
getchar();
return 0;
}
You use the wrong format specifier %d- you should use %s. Better still use fgets - scanf is not buffer safe.
Go through the documentations it should not be that difficult:
scanf and fgets
Sample code:
#include <stdio.h>
int main(void)
{
char name[20];
printf("Hello. What's your name?\n");
//scanf("%s", &name); - deprecated
fgets(name,20,stdin);
printf("Hi there, %s", name);
return 0;
}
Input:
The Name is Stackoverflow
Output:
Hello. What's your name?
Hi there, The Name is Stackov
#include <stdio.h>
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%s", name);
printf("Hi there, %s", name);
getchar();
return 0;
}
When we take the input as a string from the user, %s is used. And the address is given where the string to be stored.
scanf("%s",name);
printf("%s",name);
hear name give you the base address of array name. The value of name and &name would be equal but there is very much difference between them. name gives the base address of array and if you will calculate name+1 it will give you next address i.e. address of name[1] but if you perform &name+1, it will be next address to the whole array.
change your code to:
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%s", &name);
printf("Hi there, %s", name);
getchar();
getch(); //To wait until you press a key and then exit the application
return 0;
}
This is because, %d is used for integer datatypes and %s and %c are used for string and character types

Why doesn't scanf() take inputs from the user while dealing with strings?

My code is as follows
typedef struct
{
char name[15];
char country[10];
}place_t;
int main()
{
int d;
char c;
place_t place;
printf("\nEnter the place name : ");
scanf("%s",place.name);
printf("\nEnter the coutry name : ");
scanf("%s",place.country);
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%c",&c);
printf("You entered %c",c);
return 0;
}
If I run the program, it prompts for place name and country name, but never waits for the character input from user.
I tried
fflush(stdin);
fflush(stdout);
Neither work.
Note : Instead of a character, if I write a similar code to get an integer or a float, it prompts for values and the code works just fine.
int d;
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%d",&d);
Why does this happen? Is there anything wrong in the code?
The problem is that scanf leaves the whitespace following entered non-whitespace characters in the stream buffer, which is what the scanf(%c...) then reads. But wait a second...
In addition to being tricky to get right, such code using scanf is horribly unsafe. You're much better off using fgets and parsing the string later:
char buf[256];
fgets(buf, sizeof buf, stdin);
// .. now parse buf
fgets always gets a full line from the input, including the newline (assuming the buffer is large enough) and you thus avoid the problem you're having with scanf.
You can use string instead of character for scanf.
printf("\nEnter the place name : ");
scanf("%s%*c",place.name);
printf("\nEnter the coutry name : ");
scanf("%s%*c",place.country);
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%c",&c);
printf("You entered %c",c);
Try adding spaces before the % sign in scanf().
I have provided the modified code below.
#include <stdio.h>
#include <string.h>
typedef struct
{
char name[15];
char country[10];
} place_t;
int main()
{
int d;
char c;
place_t place;
printf("\nEnter the place name : ");
scanf(" %s",place.name);
printf("\nEnter the coutry name : ");
scanf(" %s",place.country);
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf(" %c",&c);
printf("You entered %c",c);
return 0;
}

Resources