简体   繁体   English

在scanf函数的格式字符串中,换行符的意义是什么?

[英]what is the significance of newline character in the format string of scanf function?

#include<stdio.h>
int main()
{
int a,b;
printf("enter two numbers ");
scanf("%d \n%d",&a,&b);
printf("%d  %d",a,b);
return 0;
}

when I give inputs like 3 and 5 , then the issue is that even if I give inputs without any newline character in between them then also the scanf function scans the input value , but in the formal string I have stated that the next input should be scanned after a newline character so how can the next input be scanned just after some few whitespaces . 当我提供类似3和5的输入时,问题是,即使我给出的输入之间没有任何换行符,scanf函数也会扫描输入值,但是在正式字符串中我已声明下一个输入应为在换行符之后进行扫描,因此如何在几个空白之后才能扫描下一个输入。

White-space in the scanf format string tells scanf (and family) to read and ignore white-space in the input. scanf格式字符串中的空格告诉scanf (和系列)读取并忽略输入中的空格。 It doesn't matter what kind of white-space character you use in the format: Space, newlines and tabs are all the same. 格式中使用哪种空格都无所谓:空格,换行符和制表符都相同。

However, you don't actually need it for all formats. 但是,实际上并不是所有格式都需要它。 most scanf formats automatically reads and ignore leading white-space, including the "%d" format. 大多数scanf格式都会自动读取并忽略前导空格,包括"%d"格式。

The " \\n" in the "%d \\n%d" format string will "eat" all whitespace characters as defined by isspace , including newlines. " \\n""%d \\n%d"所界定格式字符串将“吃”的所有空格字符isspace为 ,包括换行。

To force reading the integers off separate lines, use this instead: 要强制分开读取整数,请改用以下命令:

if(scanf("%d%*[^\n]\n%d",&a,&b) != 2) return EXIT_ERROR;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM