Mosab Shaheen
Mosab Shaheen

Reputation: 1174

how to scanf complete line containing spaces in c

Is there a way to scan a complete line containing spaces and store it inside one variable?

I tried a lot of things on the web like:

scanf("%[^\n]s",str);
scanf("%20[0-9a-zA-Z ]", str);
scanf("%20[^\n]", str);

nothing works.

I have something like:

#include <stdio.h>
#include <stdlib.h>
void main(){

    while (1) {
        int command = 0;
        printf("Enter a command(0-10):");
        scanf("%d", &command);
        switch (command) {
            case 4:
            {
                char message[20];
                printf("Please enter the message:");
                scanf("%s", message);
                break;
            }
        }
    }
}

when I enter value 4 for "command" variable and then some input that contains spaces for "message" array like : "hello all" then I enter in infinite loop and I don't know why?

I thought of something like scanf("%s[\n]", message); as I want to read till I reach a new line but that gives worse results (Please till me the meaning of %s[\n] in this scenario, is it same meaning of what I thought of).

So how can I scan complete line containing spaces and what is the meaning of scanf("%s[\n]",message) in general?

Update:

Actually, I tried using fgets before but it gave worse result for example:

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

void main(){

    while (1) {
        int command = 0;
        printf("Enter a command(0-10):");
        scanf("%d", &command);
        switch (command) {
            case 4:
            {
                char message[20];
                printf("Please enter the message:");
            fgets (message, 20, stdin);
                break;
            }
        }

    }

}

here the program is skipping reading "message", could you try it guys. Is there something I am missing.

Upvotes: 0

Views: 868

Answers (1)

P.P
P.P

Reputation: 121387

If you want to read a line then simple and robust solution is to use fgets(). Just don't use scanf() at all (relevant: Why does everyone say not to use scanf? What should I use instead?).

fgets() has one caveat - it'll read in the newline as well if the buffer has enough space which you need to take care.

Upvotes: 3

Related Questions