从C中的char数组中打印出一个字符串

时间:2021-05-14 15:58:41

I'm learning C programming and I'm having some issues to print a name that i store in a char array.

我正在学习C编程,我有一些问题要打印一个存储在char数组中的名称。

char nameArr[125];
for (int i = 0; i < 125; i++)
{
    if (nameArr[i] != "\0")
    {
        printf(nameArr[i]);
    }
    else
    {
        i = 125;
    }
}

This is my code in which I try to print out a name like "Joe Doe" that I already stored in the char array, but I get some errors in the compiler when I run this. If I'm not suppose to do like this, how can I print out just the name and not all the 125 slots of the array?

这是我的代码,我尝试打印出一个名为“Joe Doe”的名称,我已经存储在char数组中,但是当我运行它时,我在编译器中遇到了一些错误。如果我不想这样做,我怎么能打印出名称而不是所有125个阵列的插槽?

1 个解决方案

#1


1  

Assuming your nameArr already contains a string, which is defined as a sequence of characters ending with 0, the obvious solution is to do

假设你的nameArr已经包含一个字符串,它被定义为一个以0结尾的字符序列,显而易见的解决办法是做

printf("%s", nameArr);

or

puts(nameArr); // appends newline automatically

If your question is how you would do this by hand, it would look something like this:

如果您的问题是如何手动完成,它看起来像这样:

for (size_t i = 0; nameArr[i]; ++i)
{
    putchar(nameArr[i]);
    // or printf("%c", nameArr[i]);
}

nameArr[i] evaluates as true as long as this isn't a 0 byte. Also, always use size_t for array indices. int is not guaranteed to hold any size an object in C can have.

nameArr [i]只要不是0字节就计算为true。此外,始终使用size_t作为数组索引。 int不保证保持C中的对象可以具有的任何大小。

#1


1  

Assuming your nameArr already contains a string, which is defined as a sequence of characters ending with 0, the obvious solution is to do

假设你的nameArr已经包含一个字符串,它被定义为一个以0结尾的字符序列,显而易见的解决办法是做

printf("%s", nameArr);

or

puts(nameArr); // appends newline automatically

If your question is how you would do this by hand, it would look something like this:

如果您的问题是如何手动完成,它看起来像这样:

for (size_t i = 0; nameArr[i]; ++i)
{
    putchar(nameArr[i]);
    // or printf("%c", nameArr[i]);
}

nameArr[i] evaluates as true as long as this isn't a 0 byte. Also, always use size_t for array indices. int is not guaranteed to hold any size an object in C can have.

nameArr [i]只要不是0字节就计算为true。此外,始终使用size_t作为数组索引。 int不保证保持C中的对象可以具有的任何大小。