'Why is my print function giving the wrong output in my program to print strings?
The expected outcome is for example:
a
word
a sentence
This is the outcome tho:
aword
word
a sentence
Here's the code:
#include <stdlib.h>
#include <stdio.h>
int main() {
char letter[1], word[20], sentence[100];
scanf("%s", letter);
scanf("%s", word);
scanf(" %[^\n]s", sentence);
printf("\n %s", letter);
printf("\n %s", word);
printf("\n %s", sentence);
return 0;
}
Solution 1:[1]
At least these problems
No width limit
Never use scanf() to read user input into a string lacking a width in the format. The width should be less than the array count.
char letter[1],word[20],sentence[100];
// scanf("%s", letter);
// scanf("%s", word);
// scanf(" %[^\n]s", sentence);
scanf("%0s", letter); // "%0s" not valid. See below
scanf("%19s", word);
scanf(" %99[^\n]s", sentence); // See below also
Buffer too small for "%s"
char letter[1] only big enough for a null string "".
To read 1 character into a string, increase size
char letter[2];
scanf("%1s", letter);
s not needed
s serves no point in " %[^\n]s". Who or whatever text suggested an s is a poor source of coding in C practice.
// scanf(" %99[^\n]s", sentence);
scanf(" %99[^\n]", sentence);
Check return value
Test the return value from all scanf().
// scanf("%1s", letter);
if (scanf("%1s", letter) != 1) {
fprintf(stderr, "Failed to read into letter");
return EXIT_FAILURE;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
