简体   繁体   English

如何在 C 中的“if”中打印一个字符

[英]How do I print a char inside of an “ if ” in C

So I have this part of code inside the main function:所以我在主function中有这部分代码:

    char causatxt[10];
    if(causa == CCOLA){
        causatxt[0] = "COLA";
    }
    else if(causa == CMURO){
        causatxt[0] = "CHOQUE";
    }

    printf("\n\nEl juego ha acabado por un '%s' con los siguientes datos:", causatxt);

The problem is that I want to print the sting in causatxt but if I define char inside the if I get a non defined error and if I do what I've pasted here I can't get causatxt to be either "COLA" or "CHOQUE".问题是我想在causatxt中打印刺痛,但是如果我在里面定义 char if我得到一个未定义的错误并且如果我做了我在这里粘贴的事情,我不能让causatxt成为“COLA”或“乔克”。

I'm trying to avoid using a for loop to add the characters to every position of the array so I don't know if I'm supposed to use pointers because I'm not that experienced with those, but if using a for loop is the way to go then I guess I'll do that.我试图避免使用 for 循环将字符添加到数组的每个 position 中,所以我不知道是否应该使用指针,因为我对这些没有经验,但是如果使用 for 循环是通往 go 的方式,那么我想我会这样做。

Thanks!谢谢!

You can use strcpy from the string.h library您可以使用 string.h 库中的 strcpy

#include <string.h>
char a[100];
strcpy(a,"test");

Well if I understand correctly, you are experiencing a problem with setting a char* or char[] variable, that does not depend on if statement though.好吧,如果我理解正确,您在设置 char* 或 char[] 变量时遇到问题,但这并不取决于 if 语句。 If you want changeable text, I would rather use char* type.如果你想要可变文本,我宁愿使用 char* 类型。 So you would write:所以你会写:

char* causatxt;
if(smth)
{
    causatxt = "COLA"
}

You need to copt the strings.你需要剪断琴弦。

char causatxt[10];
if(causa == CCOLA){
    strcpy(causatxt,"COLA");
}
else if(causa == CMURO){
    strcpy(causatxt, "CHOQUE");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM