How can I read a string with spaces in it in C?

scanf ("% s", str) will not do this. He will stop reading in the first space. gets (str) does not work on a large line. Any ideas?

+5
source share
5 answers

use fgets with STDIN as a file stream. Then you can specify the amount of data that you want to read, and where to put it.

+13
source
char str[100];

try it

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

or

fgets(str, sizeof str, stdin))
+4
source

. :

1. fgets into allocated (growable) memory
2. if it was a full line you're done
3. grow the array
4. fgets more characters into the newly allocated memory
5. goto 2.

: -)

, ( , ); , "" . , ( 10 "\n"?). , .


fgetc, fgets

get a character
it it EOF? DONE
add to array (update length), possible growing it (update size)
is it '\n'? DONE
repeat
+2

? EOF, , ?

% c

c ( 1);             char,             ( NUL).             .            -, .

( ) % [

[             ; char,             ,             NUL.             .            ( ) ;             [ ] -            . ,             , ^.             ,             ; .             - ;             , .             ,             . , `[^] 0-9-] ' ``             , ''.             (,            cumflex, in)

+1
source

To read a line with a space, you can do the following:

char name[30],ch;

i=1;
while((ch=getchar())!='\n')
{
name[i]=ch;
i++;
}
i++;
name[i]='\n';
printf("String is %s",name);
+1
source

All Articles