我尝试从文本文件中读取一些数据,其中 ID 后跟名字和姓氏,但我似乎无法让 scanf 允许空格。
输入可能如下所示: 123456 名姓
scanf("%d%s", &id, fullName)
不起作用,因为它在名字和姓氏之间的空格处被截断。我想在一个字符串中包含“first last”(最好不使用 concat,因为在某些情况下不包括姓氏)。
最佳答案
您可以使用集合表示法在您的名字中指定一组允许的字符,并明确允许空格:
scanf("%d %[ a-zA-Z]", &id, fullName);
这里,[]
指定一组允许的字符(参见 man 3 scanf ),其中有一个空格 a-z
,表示“全部低于-case 字符”和 A-Z
表示“所有大写字符。
总而言之,您应该指定一个最大宽度,以避免缓冲区溢出。例如:
char fullName[64]; // allocate 64-byte array and set to 0
scanf("%d %63[ a-zA-Z]", &id, fullName);
注意使用 63 而不是 64;手册页指出它将读取指定数量的字符,然后一个 NULL 终止符:
String input conversions store a null terminator ('\0') to mark the end of the input; the maximum field width does not include this terminator.
关于c - scanf 允许单词之间有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9437919/