scanf(“%[^ \n]”,name)的区别;和scanf(“%[^ \n]”,name); [英] The differences of scanf("%[^\n]",name); and scanf(" %[^\n]",name);

查看:180
本文介绍了scanf(“%[^ \n]”,name)的区别;和scanf(“%[^ \n]”,name);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是错字。对于一个没有注意到的人,第二个有一个空格,第一个没有一个空格。

It's not a typo. And for the one who doesn't notice, there is a space on the second one, and no space on the first.

在我做作业时我会碰巧像这样:

It happens to me when i make a homework like this:

#include<stdio.h>

int main(){
int id,d,m,y;
char name[30];
printf("\tSTUDENT ID\t\t: ");scanf("%d",&id);\
printf("\tNAME\t\t: ");scanf("%[^\n]",&name);
printf("\tDATE OF BIRTH\t: ");scanf("%d/%d/%d",&d,&m,&y);
}

当我执行该代码时, NAME部分会跳至输入出生日期部分

when i do that code, the "NAME" part get skip to inputting "DATE OF BIRTH" part

但是,当我更改scanf(%[^ \n],& name);进入scanf(%[^ \n],& name);
一切正常。

But, when i change the scanf("%[^\n]",&name); into scanf(" %[^\n]",&name); everything works fine.

这怎么可能?我似乎不明白这些差异

How this could happen? I don't seem to understand the differences

注意:您可以尝试一下,告诉我它在您的电脑上是否可以正常工作,可能只是我的计算机问题或其他原因

Note: You can try it, and tell me is it works fine on yours, cause maybe its just my computer problem or something

推荐答案

scanf 格式字符串,然后 scanf 会将其与任何长度的空白匹配。因此,通过以格式开头的空格, scanf 实际上将跳过输入中的前导空格(包括来自先前输入的换行符)。

When you put a space in a scanf formatting string, then scanf will match it with any whitespace, of any length. So by putting that leading space in the format, scanf will in effect skip leading whitespace in the input (which includes the newline from the previous input).

示例:

假设您的简单程序的输入为

Lets say the input for your simple program is


123
Joe Bloggs
22/9/15

第一次拨打 scanf 会读取数字 123 ,但是将输入的换行符留在输入缓冲区的该行末尾。下次调用 scanf 获取名称时, scanf 首先会看到换行符立即返回(不消耗它) ,因此它仍将位于输入缓冲区中)。然后,您调用 scanf 读取日期,并且%d 格式会自动跳过前导空格,因此 scanf 会占用换行符,但是会看到名称,它将与十进制整数的格式不匹配,然后退出,而不读取数据。

The first call to scanf read the number 123, but leaves the newline you enter to end that line of input in the input buffer. When you next call scanf to get the name, then scanf will first see that newline end return immediately (without consuming it, so it will still be in the input buffer). Then you call scanf to read the date, and the "%d" format automatically skip leading whitespace, so scanf will consume the newline, but then see the name and it will not match the format for decimal integers and exit, not reading the data.

通过在读取名称时在格式中添加前导空格,第二个 scanf 调用将读取(并忽略)先前输入的换行符,然后正确读取名称,将终止于第二行的换行符留在输入缓冲区中,然后在下一次调用 scanf 时将其跳过,从而正确读取日期。

By adding that leading space to the format when reading the name, the second scanf call will read (and ignore) the newline from the previous input, and then read the name properly, leaving the terminating newline from the second line in the input buffer which is then skipped by the next call to scanf which properly reads the date.

这篇关于scanf(“%[^ \n]”,name)的区别;和scanf(“%[^ \n]”,name);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆