【问题标题】:C: printf is not printing the answer to the input by user [duplicate]C:printf没有打印用户输入的答案[重复]
【发布时间】:2019-11-22 00:50:45
【问题描述】:

我有一个代码,如果用户键入“什么是苹果”,它应该回答“苹果是水果”,但对于这种情况 在文本文件中存储为 [what] 的内容。看起来像这样

[what]
apple = apple is a fruits.

下面是我的代码。它没有打印出“苹果是水果”。我能知道我的错误在哪里吗?

char intent[255];
char key1[255];
char key[255];
char inv[3][10] = { "what","where","who" };

snprintf(intent, sizeof(intent), "[%s]", inv[0]);
printf("%s\n", intent);

scanf("%s",&key1);

if (strcmp (intent == "[what]" && key == "apple") == key1) {
    printf ("apple is a fruits");
    }

【问题讨论】:

  • 这不是你在 C 中比较字符串的方式。
  • 嗨,我已经编辑了代码,但它不起作用,并且出现错误“访问冲突读取位置 0x00000000”
  • 修改后的代码不应编译——strcmp() 需要两个参数,而您只提供一个。您应该使用strcmp(intent, "[what]") == 0 && strcmp(key, "apple") == 0 作为比较两对字符串的条件。
  • 你应该从参考中学习,而不是反复试验

标签: c arrays csv


【解决方案1】:

正如 Shawn 在对您的问题的评论中所说,您无法使用 == 运算符比较 C 字符串,您需要使用 strcmp() 函数。

另外,snprintf 的第二个参数应该是函数不应超过的字符数,这不是 sizeof(intent) 所做的。 sizeof(intent) 不会给你意图数组的大小,但如果我是正确的,它会返回一个 char* 指针的大小。 只需将 sizeof(intent) 替换为 255 或使用常量 MAXSIZE。

另外,scanf 在写入 char 数组(即字符串)时不需要 & 运算符,scanf("%s", key1); 是正确的,因为数组的名称​​是地址。

【讨论】:

  • 在这种情况下,由于intent 是一个数组,而不是一个指针,sizeof(intent) 是 255,使用它是合适的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多