C 编程 - scanf() 中空格的作用 [英] C Programming - Role of spaces in scanf()

查看:94
本文介绍了C 编程 - scanf() 中空格的作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码:

#include <stdio.h>
int main()
{
  int a, b;
  printf("Enter values of a and b\n");
  scanf(" %d%d ", &a, &b); // Note the two spaces before and after %d
  //     ^This^
  printf("a = %d b = %d\n", a, b);
  return 0;
}

程序运行如下:

aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Enter values of a and b
1
2
3
a = 1 b = 2

我的问题是为什么它需要三个输入而不是两个(两个 %d 在 scanf() 中),即使它需要三个,为什么它跳过最后一个?

My question is that why is it taking three inputs instead of two (two %d is in scanf() ) and even if it is taking three, why is it skipping the last one?

推荐答案

格式字符串中的空格表示跳过输入中的任何空格序列(空格、换行符、制表符),并在到达第一个时停止扫描非白字符或输入的结尾.下一个字符留在输入缓冲区中,因此它可以由下一个格式运算符(如果有)或下一个输入操作(如果您要在 getc() 之后调用 getc()code>scanf(),它会读取 '3' 字符.

Space in a format string means to skip over any sequence of whitespace (spaces, newlines, tabs) in the input, and stops scanning when it gets to the first non-white character or the end of the input. That next character is left in the input buffer, so it can be read by the next format operator (if there is one) or the next input operation (if you were to call getc() after your scanf(), it would read the '3' character.

当您在格式字符串的末尾放置一个空格时,它会跳过 2 之后的换行符,并继续扫描直到到达下一个非白色字符.所以它必须在它停止之前到达3.

When you put a space at the end of the format string, it skips over the newline after 2, and keeps scanning until it gets to the next non-white character. So it has to get to the 3 before it stops.

这篇关于C 编程 - scanf() 中空格的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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