错误:未为C指定与字符串文字的比较结果 [英] error: result of comparison against a string literal is unspecified for C

查看:56
本文介绍了错误:未为C指定与字符串文字的比较结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图与C开个玩笑,但我不知道自己在做什么错.我看到错误"错误:未指定字符串文字的比较结果",并且不知道如何解决它,有人可以帮忙.

So I am trying to create a little joke with C and I don´t know what I am doing wrong. I see the Error "error: result of comparison against a string literal is unspecified" and do not know how to fix it, can someone help.

#include<stdio.h>
#include<cs50.h>
int main(void){
    string a = get_string("ENTER YOUR NAME FOR READING\n");
    if (a == "david")
    ;
    {
        printf("...");
    }
}

推荐答案

您的代码存在三个问题:

Your code has three issues:

if(a =="david")

a 衰减到指向数组 a 的第一个元素的指针.

a decays to a pointer to the first element of array a.

大卫" 是字符串文字.

使用 if 语句,您尝试将数组 a 的地址与字符串文字"david" 的地址进行比较.字符串比较模式在C语言中无法正常工作.

With the if Statement, you attempt to compare the address of the array a by the address of the string literal "david". String comparison dies not work that way in C.

使用 strcmp()-标头 string.h 比较字符串.

Use strcmp() - header string.h to compare strings.

strcmp()返回0.要使 if 条件变为 true ,您需要使用求反运算符.

strcmp() returns 0 if the strings are equal. To make the if condition turn true you need to use ! negation operator.

if 条件和 if 正文之间的; 放错了位置.删除它.

There is a misplaced ; between the if condition and if body. Remove it.

不建议使用 cs50.h .如果不需要显式使用它,请不要使用它.

The use of cs50.h is deprecated. If you are not required to use it explicitly, leave your hands off from it.

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

int main (void) {
    char a[20];

    printf("ENTER YOUR NAME FOR READING:\n");

    if (!fgets(a, sizeof a, stdin))
    {
         fputs("Failure at input", stderr);
         // further Error routine.
    }

    a[strcspn(a, "\n")] = 0;

    if (!strcmp(a,"david"))
    {
        printf("...");
    }
}

这篇关于错误:未为C指定与字符串文字的比较结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆