poorvank
poorvank

Reputation: 7602

Different types of scanf usage in C

I know in order to use scanf to get input strings having spaces we use a call such as:

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

which will match all the characters up to new line. But I found another call of scanf:

scanf("%[ A-Za-z]",str);

For me both are working fine!But I am not able to figure out what is the difference between the two!?

Which method is should I use while dealing with string with spaces?

Upvotes: 0

Views: 694

Answers (2)

kandelvijaya
kandelvijaya

Reputation: 1585

Its better if you use the first one which omits newline and accepts every character besides it. That means you can supply a complete line and scanf will end read in when you press enter. Its similar to gets() function which can be included from string.h

Upvotes: 0

user529758
user529758

Reputation:

what is the difference between the two!?

The first one scans everything up to a newline character, the second one scans letters and space only.

Which method is should i use while dealing with string with spaces?

Neither one, have a look at fgets() instead:

char buf[LINE_MAX];
fgets(buf, sizeof(buf), stdin);

Upvotes: 5

Related Questions