c - 为什么 get_long_long("") 打印 2 次?
问题描述
get_long_long("")
下面的代码打印了 2 次,我不知道为什么。它打印 , Please enter your credit card number..."
, 2 次。(注意:我不是在骗人,我们是在为 AP 计算机科学课做这个项目,基本上是在编写一个程序来检查卡是否合法。)
这不是完整的代码,只是开始询问他们拥有哪个卡提供商,然后将使用该信息来确定卡是否合法。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
char type1[100]; //array used to store and then compare which card is being used
char visa[25] = "Visa";
char amex[25] = "Amex";
char master[25] = "Mastercard";
long long card;
int main(void)
{
printf("Is your card Visa, Mastercard, or Amex?\n");
//read the card type then store it in type array
scanf("%s", type1);
if (strcmp(type1, master) == 0 || strcmp(type1, visa) == 0 ||
strcmp(type1, amex) == 0)
{
card = get_long_long("Please enter your credit card
number\n");
}
do
{
printf("Is your card Visa, Mastercard, or Amex?\n");
scanf("%s", type1);
}
while (strcmp(type1, master) == 0 || strcmp(type1, visa) == 0
|| strcmp(type1, amex) != 0);
解决方案
scanf
转换%s
匹配一系列非空白字符(在跳过任何前导空白之后)并在遇到尾随空白时停止。这意味着任何尾随空格,例如行尾的换行符,都不会被读取。即使不知道 non-standard 的内部结构get_long_long
,我几乎可以肯定它首先遇到换行符并再次询问,因为这看起来与用户只需按 enter 而不输入任何其他内容相同。
推荐阅读
- java - While 循环,IndexOutOfBoundsException:索引:1,大小:1
- ruby-on-rails - Firefox 是默认的,但仍然得到 WebDriverError: unable to connect to chromedriver 127.0.0.1:9515
- c# - 使用派生类中的不同类型保持在抽象中定义的默认行为
- applescript - 如何解决 AppleScript <
> 命令在脚本编辑器中工作,但保存为 .app 时失败? - visual-studio-code - vscode.WorkSpaceEdit:它是否适用于当前未在编辑器中打开的文件
- ffmpeg - 是否可以强制 ffmpeg 对 H.264 输入流使用硬件解码?
- python - 多项式回归打印特征名称和学习函数的截距
- django - 用于循环的 django 模板语言
- jquery - 滚动条仅在顶部
- bash - 我如何获得用完 cygwin 的过程的 Windows PPID?