【问题标题】:A program that compares 2 strings in CC中比较两个字符串的程序
【发布时间】:2016-12-21 16:53:41
【问题描述】:

这是我的程序:

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

int main(){
    char alegere[10];
    int a;
    printf ("Alege natura matricei tale: (Numere/Caractere)");
    scanf ("%s", &alegere[10]);
    if (strcmp(alegere, "Numere") == 0){
        printf("a");
    } else 
        printf ("b");
    return 0;
}

它应该将我从键盘输入的字符串与字符串“Numere”进行比较,但如果我输入字符串“Numere”或任何其他字符串,结果将是相同的,我将打印“b” ...那我做错了什么?

【问题讨论】:

  • @user3121023 我得到了同样的结果
  • 这段代码编译正确吗?字符串比较应该是 (strcmp(alegere, "Numere") == 0)..
  • #include &lt;string.h&gt;
  • @WeatherVane 我有,只是忘了在这里输入。
  • 还有什么你忘记的吗,比如)?请发布显示问题的Minimal, Complete, and Verifiable example。 “可验证”是指,因此我们不会回答虚构的问题。

标签: c compare


【解决方案1】:

三件事:

  1. 按照 cmets 中的建议,您应该在 scanf 中使用 "%9s" 而不是 "%s"。这样可以确保输入的字符数不会溢出您的数组alegere,它只能容纳 10 个字符。 (为什么是 9 而不是 10?因为 C 字符串是 null terminated。)
  2. 您在致电strcmp 时缺少)
  3. &amp;alegere[10] 不做你想做的事; &amp;alegere[10]alegere[10] 的内存地址,或者是数组末尾的一个地址。这意味着您的 scanf 调用未定义的行为。将其替换为 &amp;alegere[0] 或更简单的 alegere

更正的代码:

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

int main(){
    char alegere[10];
    printf ("Alege natura matricei tale: (Numere/Caractere)");
    scanf ("%9s", alegere);
    if (strcmp(alegere, "Numere") == 0){
        printf("a");
    } else
        printf ("b");
    return 0;
}

【讨论】:

  • &alegere[0] alegere + 0 alegere
  • 对不起,我写得很快。你写的第三个提示是我的问题,现在我明白为什么它不起作用了
【解决方案2】:
  1. 大括号问题改变了这一点

if (strcmp(alegere, "Numere" == 0)

if (strcmp(alegere, "Numere") == 0)

2。扫描内存未指向地址的开头

scanf ("%s", &amp;alegere[10]);scanf ("%s", alegere); // %9s 是其他用户的一个很好的建议

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    相关资源
    最近更新 更多