c-先得到一个十进制数,然后是字符串,然后是带空格的十进制数



在使用scanf时想用空格存储一个字符串,但我没能做到。如果我键入"25 byllie street 5093 New York",我在变量中只得到byllie和New

#include <stdio.h>
#include <stdlib.h>
#include "Adress.h"
int main (void)
{
Adress dom;
printf("Type number space string number string and store n);
scanf("%d %s %d %s",&dom.number, dom.street, &dom.number2, dom.town ) ;
}

">在我的cmd上,我要写例如"14 afee 50 fafeef a",我想得到dom.number=14,dom.street="afe afee",dom.number2=50和dom.town="fafeef a">

">如果我键入"25 byllie street 5093 New York",我在变量中只得到byllie和New!*">

%s格式说明符不捕获以空格分隔的字符串内容。请改用%[

还不如先通过fgets将整个输入捕获为字符串,并将其存储到缓冲区中,以确保安全的输入消耗:

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

然后使用sscanf():解析字符串

sscanf(buf,"%d %[^0-9]%d %[^0-9n]",&dom.number, dom.street, &dom.number2, dom.town ) ;

不要忘记检查sscanf():的返回值

if (sscanf(buf,"%d %[^0-9]%d %[^0-9n]",&dom.number, dom.street, &dom.number2, dom.town ) != 4)
{
fprintf(stderr ,"Error at scanning the input string!");
} 

最新更新