This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 2 months ago.
I have a sample weird code like this:
#include<stdio.h>
int main(){
int t;
scanf("%d", &t);
while(t--){
char s[1];
scanf("%s", s);
}
}
I have test that if I have t from input that > 1 ( like t = 3) then put a single character to s, then the program ends, while t hasn't downed to 0 yet. Could anyone explain for me what happens here. Thanks for your help!
Change char s[1]; to char s[100]; or other length to allow at least as many characters as you will enter plus one for the terminating null character.
When scanf processes a %s, it appends a terminating null character to the end of the characters it matches to the %s. Since you declared s as char s[1];, there is no reserved room for the terminating null character, and scanf attempts to write beyond the reserved space.
Then the behavior of your program is not defined by the C standard.
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
This question might look stupid but I am not used to work with C and I'm losing my mind here not knowing what is wrong.
Basically what I want is to get a number from the user, then a string, the user may write whatever he feels like, I want to keep just the first caracter of that string.
My code is the following:
#include <stdio.h>
int main()
{
int b, n;
char frase [2];
scanf("%d", &n);
fgets(frase, 2, stdin);
puts(frase);
return 0;
}
My problem is, after the fgets the program stops, no matter what I have after it, it only stops, no error messages or anything. What is happening?
What is happening?
Your code will:
For an input 123 abc:
Store 123 in n, store the space in frase followed by a null byte. Then it will print that single space and end its execution with no errors.
For an input 123 Enter abc:
Store 123 in n and store in frase the newline character \n added to the buffer when you pressed Enter, followed by a null byte, next it will print that \n and end its execution with no errors.
So it doesn't just stop, it does what it's supposed to do.
What you shoud do, to make your code more robust, is to also parse the number with fgets, and convert it with sscanf or strtol:
int n = 0;
char buffer[20];
char frase[2];
fgets(buffer, sizeof buffer, stdin);
if(sscanf(buffer, "%d", &n) != 1){
//value not parsed
}
fgets(frase, sizeof frase, stdin);
puts(frase);
Using scanf to parse inputs is rarely, if ever, a good ideia.
The fgets is grabbing the newline character that is in the buffer after scanf reads the int. Putting a getchar() before your fgets should fix the problem.
This question already has answers here:
Why does scanf ask twice for input when there's a newline at the end of the format string?
(7 answers)
Closed 5 years ago.
I am trying to simply get a user input string. The string is saved (scanf) when the person hits enter or the string hits the NULL character. Yet, when I run my program, and type in the string, it continues input until I type \n or \0 (whichever I have in my if statement. Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MSL 30
char intersperse(char);
char widen_stars(char);
int main(int argc, char *argv[])
{
char *p, *q, *str1[MSL], *str2[MSL];
if(str1[MSL+1] != '\0'){
printf("Please enter a string of maximum 30 characters: ");
scanf("%s\n", str1[MSL]);
}
printf("%s\n", str1[MSL]);
}
This is by no means finished code, i'm just in the process of writing my program when I snagged this annoying bug. The +1 on my MSL is to make sure the NULL character is read so my string doesn't yell at me, idk if it's necessary, but it's a precaution. Thank you answerers.
There are various problems with your code, not just a simple bug. I'll try to describe some of them here.
Turn on compiler warnings. For example, if your array is size 30, there is no element at index 30 (indexes would go from 0 to 29). Your compiler could have warned you about that and other problems.
Store a string in a char array or pointer, but not in a char pointers array. When you wrote:
char *str1[MSL]
You are creating an array of pointers to char, or an array of strings. However, since you're dealing with pointers to char as strings, you'd need to allocate space for them yourself. That's another concept. You probably meant to write an array of char like this:
char str1[MSL]
char *p, *q, str1[MSL], str2[MSL]; /* in your declaration */
Enter at maximum 29 characters. If your string holds 30 char, and you need 1 to mark the null at the end, you've got 29 remaining usable chars. Or… change MSL to 31.
Consider dropping the \n from your scanf format. It will make it read all whitespace (which is what \n represents in a format) waiting for the next non-whitespace. Thus, the input somestring<enter> for example won't be sent directly to your program until the next non-whitespace or EOF.
Give scanf an address. That could be just the array name (which translates to the first element address) or a pointer if you were working with them.
scanf("%s", str1);
scanf("%s", strptr); /* strptr is a char pointer pointing
to previously allocated space */
You can limit the length of what scanf reads. To be safe:
scanf("%29s", str1);
Don't use uninitialised data in comparisons. When you wrote if(str1[MSL+1] != '\0'), what did you expect str1 to contain if you had never stored anything yet?
int
main(int argc, char **argv)
{
char *p, *q, str1[31], str2[31]; /* a lot of unused variables */
printf("Please enter a string of maximum 30 characters: ");
scanf("%30s", str1);
printf("%s\n", str1);
return 0;
}
This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 6 years ago.
I'm with a little problem while doing an excercise to learn C.
The problem is: I need to read a string from the user, but if he types just a space, I need to print a space. That's okay in theory.
But, when I type the space while the program is running, it doesn't understand it as a string and it keeps waiting for me to type other things.
I'm using the scanf("%[^\n]", string_name_here);
I appreciate your help, and have a nice day! o/
And sorry for my bad english, I hope you can understand this :)
Using char *fgets(char *str, int n, FILE *stream) will make your day.
According to man :
fgets() reads in at most one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A terminating null byte ('\0') is stored after the last character in
the buffer.
Example program
#include <stdio.h>
#define MAXSTR 21
int main(void)
{
char my_str[MAXSTR] = {'\0'};
fgets(my_str, MAXSTR, stdin);
return 0;
}
Input :
Claudio Cortese
Output :
Claudio Cortese
This question already has answers here:
Why 2nd scanf doesn't work in my program?
(3 answers)
Closed 8 years ago.
I am try the code below.But when I input the integer,then program does not ask for character.Program execute the printf line.How should i avoid above problem?.
#include <stdio.h>
void main()
{
char a[5];
int p;
printf("data\n");
scanf("%d",&p);
scanf ("%c",&a);
printf("--> %c %d\n",a,p);
}
Put a space in scanf like this:
scanf (" %c",&a);
^-------note
So that the trailing newline is eaten up. Once you hit enter after giving the integer input - there is a trailing newline character in the buffer which the second call to scanf reads. Also main as per ISO should return int
Also this statement is incorrect:
char a[5];
printf("--> %c %d\n",a,p);
You are reading a char and printing an array. You simply need:
char a;
printf("--> %c %d\n",a,p);
If you want to read (or take input) array of chars then use fgets. For char a[5] do something like:
fgets (a, 5 , stdin)
Since fgets is buffer safe.
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Store data in array from input [duplicate]
(2 answers)
Closed 8 years ago.
I have the following code:
#include<stdio.h>
#include "commonf.h" //So, this is the way you include from a directory?
void main(){
println("Welcome to Number Guesser v 0.1 ");
println("Think of a number between 0 and 100 (and please, make it an integer!)");
println("Legend: Y=Yes B=Bigger than that S= Smaller than that");
int guessed=0;
float curnum=100.0;
char cursign='?';
while(cursign!='y'){
if(cursign=='?' || cursign=='s'){
curnum=curnum/2;
}
else if(cursign=='b'){
curnum=curnum+curnum/2;
}
else{
printf("You are wrong. Stop it. %c . TEESST",cursign);
}
char askstring[4096];
sprintf(askstring,"%s%f%s","Is your number ",curnum," ? (y/b/s)");
println(askstring);
scanf("%c",&cursign); //Scanf has to expect a new line for some reason.
}
}
(I pasted all of it, since I am a c noob)
If the code looks like this, the loop will execute twice per user input, once with cursign= to whatever the user entered, and once with it equal to \n.
If I change the scanf line to
scanf("%c\n",&cursign);
It asks for the first input twice, then works as a charm. What's the problem, and what should I do?
Change this scanf("%c\n",&cursign); to this scanf(" %c",&cursign);. This will eat up the trailing newline character.
Also as per standard main should return an int (even though this is not the reason for your problem). According to C standards main should be int main(void) or int main(int argc, char* argv[])
When you enter a character like y and hit the ENTER key, a character (which you entered) and a character (which is the enter keystroke - the newline character) gets placed in the input buffer. The first character gets consumed by the scanf but the newline remains in the input buffer so what happens is that the next time you enter something there 3 characters newlinechar + 'y' + newlinechar. So that makes scanf behave funny.
This is a great link from Grijesh - C Printf and Scanf Reference