1

I wrote and compiled this program in codeblocks:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char myChar[155];
    scanf("%s", myChar);
    printf("%s\n", myChar);
    return 0;
}

I have tried many things but for some reason when you input a string with more than one word, the console only outputs the first word. Is it the fault of the compiler or am I doing something wrong here?

3
  • 3
    You're doing something wrong. You should probably read the documentation to see what %s actually does. cplusplus.com/reference/cstdio/scanf Commented Mar 4, 2021 at 18:50
  • That's how scanf with %s works. It only stores one [whitespace separated] word. To input a whole line string such as: Mauser Maschine [scanf will only get Mauser], use fgets [and strip the newline]. Then, you'll have the full string [with the spaces]. In other words, try: fgets(myChar,sizeof(myChar),stdin); myChar[strcspn(myChar,"\n")] = 0; Commented Mar 4, 2021 at 18:57
  • The f part of scanf is there for a reason. Commented Mar 4, 2021 at 19:16

1 Answer 1

4

Switch to

scanf("%154[^\n]", myChar);

154 to avoid buffer overflows - [^\n] scans until a new line.

or better yet, use fgets and strip the trailing new line:

if (fgets(myChar, sizeof myChar, stdin))
{
    myChar[strcspn(myChar, "\n")] = '\0';
}

Notice that scanf and fgets can fail, in such case you end up printing an uninitialized value (undefined behaviour), to avoid problems with the standard input always initialize your strings:

char myChar[155] = "";
Sign up to request clarification or add additional context in comments.

8 Comments

Thx for responding guys. I don't know how to close a question so see ya!
@AyxanHaqverdili Too bad they left so soon, they were very pretty :P
@DavidRanieri Are you talking about the fake profile picture? I was just trying to get your answer accepted :D
@AyxanHaqverdili I apreciate it, and yes, I was talking about the profile picture :D
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.