首页 > 解决方案 > 为什么 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);

标签: ccs50

解决方案


scanf转换%s匹配一系列非空白字符(在跳过任何前导空白之后)并在遇到尾随空白时停止。这意味着任何尾随空格,例如行尾的换行符,都不会被读取。即使不知道 non-standard 的内部结构get_long_long,我几乎可以肯定它首先遇到换行符并再次询问,因为这看起来与用户只需按 enter 而不输入任何其他内容相同。


推荐阅读