Domanda

I am trying to use scanf() for input. It worked perfectly except when I typed a space. Then it doesn't pick up the string -- why?

char idade;
scanf("%c", &idade);

I tried do to this:

scanf("%[^/n]c", &idade);

But it did not work. For example, when I typed in "Hello world", my string only contained "Hello" All I want is for it to recognize the space and take the full string. How can I do that?

È stato utile?

Soluzione

The %c conversion specifier in the format string of scanf does not skip (read and discard) the leading whitespace characters. If you have a leading whitespace character in the format string, then this means scanf will skip any number of leading whitespace characters in the input which is probably what you want. Assuming you want to read a single character -

char idade;
scanf(" %c", &idade);
   //  ^ note the leading space 

However, if you want to read an input string from stdin, then

char input[50+1];  // max input length 50. +1 for the terminating null byte

// this skips any number of leading whitespace characters and then
// reads at most 50 non-whitespace chars or till a whitespace is encountered - 
// whichever occurs first, then adds a terminating null byte
scanf("%50s", input);  

// if you want to read a input line from the user
// then use fgets. this reads and stores at max 50 chars
// or till it encounters a newline which is also stored - whichever
// occurs first, then it adds a terminating null byte just like scanf
fgets(input, sizeof input, stdin);

Please read the man page of fgets.

Altri suggerimenti

There's a small error in your line

scanf("%[^/n]c", &idade);

It should read

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

Backslash '\' is the escape character, not '/'. You have to put '\n' (line feed character) in the exclusion list or else scanf will not know when to stop parsing. Your expression excluded '/' and 'n' as input characters.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top