Michael Sazonov
Michael Sazonov

Reputation: 1533

Why the input breaks after a space character

Hello guys!

Here:

#include <stdio.h>

char* getStr( char *c ){
    scanf( "%s" , c );
    return c;
}

int main(){
    char str[ 100 ];
    getStr( str );
    printf( "%s" , str );
    return 0;
}

Could you please explain why is the string printed only until the first "space". i.e.

input: asd asd

output: asd

Upvotes: 2

Views: 246

Answers (4)

user2493662
user2493662

Reputation: 21

If you want to take input strings with spaces you can also use fgets() function as shown below:

char str[50];
printf("Enter a string: ");
fgets(str,50,stdin);

printf("%s",str);  //print the accepted string

Upvotes: 0

Amadan
Amadan

Reputation: 198476

Because that's what scanf does. If you want to read a string till newline, use gets EDIT: or its buffer-overflow-safe cousin fgets (thanks, @JayC)

Upvotes: 7

Matt
Matt

Reputation: 7160

From the scanf man page:

Matches a sequence of non-white-space characters

That answers your question.

If you need to match whitespace as well then you may need to process it in a loop, or just read it using more traditional methods.

Upvotes: 2

Jeff Foster
Jeff Foster

Reputation: 44736

That's the contract of scanf (see http://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html). It reads until the next whitespace encountered.

You could change your format string to read in two strings as "%s %s" which will read two strings separated by whitespace.

Upvotes: 14

Related Questions