【问题标题】:Prompt for input and print a response with only one printf()?提示输入并仅使用一个 printf() 打印响应?
【发布时间】:2015-05-28 03:24:48
【问题描述】:

仅限 C 代码:询问用户是否已婚。用户必须输入 0 表示假。用户必须输入任何其他字符为真。只使用一个 printf。

好的,所以我总是将 stackoverflow 作为最后的手段,因为我正在努力解决这个问题。这是我想出的,但我得到了错误,我做了其他事情,比如取出scanf("%f", &t),因为这本质上是不必要的。我还发了char married[3];char married[] =";相反,但这不起作用。

这是我的代码:

#include <stdio.h>
#include <string.h>

int main()
{
    char married[3];

    unsigned long t;
    int f;
    scanf("%f", &t);
    scanf("%d", &f);

    printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married? %s", married);

    if (f == 0)
    {
        married == "no";
    }
    else
        married == "yes";
    return 0;
}

感谢您的帮助。请放轻松我只是学习...

【问题讨论】:

  • married == "no"; 测试它们的相等性,这永远不会是真的,然后把结果扔掉。这显然不是你想要的。
  • 程序需要的输出是什么?无论如何,任何解决方案都可能在printf 之后有scanf。因为当然对用户的提示必须在读取用户输入之前出现。
  • 为什么你的程序它要求用户输入一个数字之前等待用户输入一个数字?
  • 为什么在你(尝试)给它一个值之前显示married
  • 每件事的顺序似乎都错了。在尝试设置之前打印married

标签: c string printf


【解决方案1】:

我不确定您是否正确解释了这个问题。它说要打印此人是否已婚。这就是预期的输出。它建议您可以使用一个 printf 来做到这一点。这并不意味着整个程序只有一个 printf,因此您可以为用户提示使用另一个 printf。这只是意味着避免使用两个 printfs 作为输出(一个用于 YES,另一个用于 NO)。一种方法是使用 ?运算符。

例如:

#include <stdio.h> 
#include <string.h>

int main(void)
{
    int married = 1;

    printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?");
    scanf("%d", &married);

    printf("You %s married\n", married ? "ARE" : "ARE NOT");

    return 0;
}

【讨论】:

    【解决方案2】:
    #include <stdio.h> 
    #include <string.h>
    
    int main() {
        char married[4]; //Space for 'yes' + the NUL-terminator
        //unsigned long t; Why do you have this?
        int f = 1; //Initialize variables
    
        //scanf("%f", &t); ??
        //scanf("%d", &f); Wrong place
    
        printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?"); //Remove %s and the argument. You are trying to print an uninitialized array
        scanf("%d", &f); //scan input after printing
    
        if (f == 0) 
            strcpy(married, "no");
        else
            strcpy(married, "yes"); //Copy strings using strcpy function
    
        return 0;
    }
    

    【讨论】:

    • 然而,程序什么也没输出(不是你的错,这就是 OP 目前的做法,请参阅问题的第二条评论)。
    • 谢谢老兄!是的,就像我说的那样,我删除了它,但我正在撤消所有编码以回到它工作的地方;这就是为什么我在上面解释了 unsigned long t 的原因。否则,伟大的工作。感谢您教我字符串复制:)。但是,我收到这个错误Warning 2 warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. 我猜这个代码是在假设用户默认结婚,bc int f = 1;,但我不知道如果不是扫描输入是否会被发现初始化为整数。
    • @mwf1234:在这种情况下,它的意思是——你。见What does OP mean?
    • 如果您所指的第二条评论是@alanau,那么这并不能解决问题。 Coolguy 在上面的代码中显示了这一点
    • @mwf1234: 1. “解决问题”的说法毫无意义。 2.您的问题和上面的答案(依赖于您问题中的代码)都没有解决这个问题 - 代码输出NOTHING!!!
    猜你喜欢
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多