使scanf在字符串中间拾取空格

时间:2014-04-05 17:13:12

标签: c string whitespace scanf

我正在尝试使用scanf()作为输入。除了输入空格外,它工作得很好。然后它没有拿起字符串 - 为什么?

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

我试过这样做:

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

但它没有用。例如,当我输入“Hello world”时,我的字符串只包含“Hello”所有我想要的是识别空格并获取完整的字符串。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

格式字符串%c中的scanf转换说明符不会跳过(读取和丢弃)前导空格字符。如果格式字符串中有前导空白字符,那么这意味着scanf将跳过输入中任意数量的前导空白字符,这可能是您想要的。假设你想读一个字符 -

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

但是,如果您想从stdin读取输入字符串,那么

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);

请阅读fgets的手册页。

答案 1 :(得分:1)

你的行中有一个小错误

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

应该阅读

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

反斜杠'\'是转义字符,而不是'/'。 您必须在排除列表中添加'\ n'(换行符),否则scanf将无法知道何时停止解析。 您的表达式将“/”和“n”排除在输入字符之外。