c - 将字符串放在 if/else 括号内?

标签 c string if-statement char

我是 TurboC 的初学者,我的问题是在 if/else 语句中放入一个“单词”(字符串),然后其输出在 printf 上

这是我的错误代码

#include <stdio.h>

main(){
    int enter;
    string thisword;

    clrscr();
    printf("Press number 1 then enter ");

    scanf("%i",&enter);

    if(enter==1){
        thisword = 'Thanks';
    }
    else{
        thisword = 'Error';
    }


    printf("\n%s",thisword);

    getch();
    return.0;
}

我不想将 printf 作为语句放在每个 if/else 括号中,例如

#include <stdio.h>

main(){
    int enter;

    clrscr();
    printf("Press number 1 then enter ");

    scanf("%i",&enter);

    if(enter==1){
        printf("\n Thanks");
    }
    else{
        printf("\n Error");
    }    
    getch();
    return.0;
}

最佳答案

我不知道Turbo C,但是C中不存在“string”类型。

  • 使用 char * 类型
  • 对字符串使用双引号“而不是单引号”

您的代码也可以工作。

#include <stdio.h>

int main() {
    int enter;
    char *thisword;

    printf("Press number 1 then enter ");
    scanf("%i",&enter);

    if (enter == 1) {
        thisword = "Thanks";
    }
    else {
        thisword = "Error";
    }
    printf("\n%s",thisword);
    return.0;
}

关于c - 将字符串放在 if/else 括号内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42716006/

相关文章:

c++ - 在 C 代码中使用用 C++ 编写的函数

c - 附加到字符串的未打印字符

在 C 上比较字符串和 if

c - 使用 if 语句中定义的变量

c - 读取未知行数

c - char 字符串中的 ascii 代码

.NET字符串串联(+&+ =)与StringBuilder

python - 如何检查列表是否包含空字符串

java - 仅当检查整个数组时才使用 Else 语句

mysql - 如何在此语句上创建条件 IF THEN?