【问题标题】:How do you store user input as a variable in c?如何将用户输入存储为 c 中的变量?
【发布时间】:2018-09-18 08:47:19
【问题描述】:

我是一个非常新手的程序员,对我在做什么一无所知。除了阅读文档。

我的程序没有让用户有时间立即输入 unwires,它只是说“否”的答案。我做错了什么?

我制作这个程序是为了给我的朋友开个玩笑(就像 AI 出了问题)

这是我的代码:

#include <stdio.h>

int main() {

    int yorn;

    printf("do you have friends? please awnser yes or no.");
    scanf("%d", &yorn );

    if (yorn = "yes") {
        printf("no, you dont. please reload the program if you want to change your awnser.");
    }
    else if (yorn = "no") {
        printf("i can be your friend. your BEST friend.");
    }
    return 0;
}

【问题讨论】:

  • 这取决于输入的类型。 (双关语,你的变量类型和你描述的用户类型不匹配)
  • 真@BenVoigt。我已经回答建议他进行更改。
  • 在启用警告的情况下编译会在这里发现多个问题(滥用单个 = 并将指针值分配给整数)。值得学习如何将编译器配置为最高警告级别(gcc 中的-Wall)并始终注意警告。

标签: c variables input store


【解决方案1】:

为了比较,你有两个使用 strcmp 而不是 =。此外,您将 int 类型用于 yorn 并与字符串进行比较。将 yorn 类型更改为 char[] 并在 scanf 中读取为 %s

将您的代码更改为遵循代码。仔细看就明白了:

int main() {

    char yorn[20]; //set max size according to your need

    printf("do you have friends? please awnser yes or no.");
    scanf("%19s", yorn); // Use %s here to read string.

    if (strcmp(yorn, "yes") == 0) { //Use ==
        printf("no, you dont. please reload the program if you want to change your awnser.");
    }
    else if (strcmp(yorn,"no") == 0) { // Use ==
        printf("i can be your friend. your BEST friend.");
    }
    return 0;
}

【讨论】:

  • 不能在C中直接比较字符串,使用strcmp字符串操作。
  • 现在它会编译,但是那些== 操作符会做一个指针比较,而不考虑存储在这些位置的字符串。
  • 你添加了一个错误,当有人输入超过 20 个字符时。
  • @DanielH 答案是为初学者准备的。指针和内存分配的概念我没用过。
  • @PassionInfinite 不需要太多知识就能明白,如果声明为char[20],则需要在scanf 中说%19s
猜你喜欢
  • 2022-11-23
  • 2021-03-17
  • 1970-01-01
  • 2017-01-07
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
相关资源
最近更新 更多