C语言 打印字符数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23590006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:04:40  来源:igfitidea点击:

Printing Char Array Element

carrays

提问by user1117742456

I've been hung up on this for the past two hours, and it's really starting to irritate me. I'm using standard C, trying to print a char array's element.

过去两个小时我一直挂在这上面,这真的开始让我恼火了。我正在使用标准 C,试图打印一个字符数组的元素。

The following is a snippet that works(prints entire array),

以下是一个有效的片段(打印整个数组),

CreditCard validate_card(long long n) {

    CreditCard cc; // specify new credit card
    cc.n = n; // specify card num as passed
    cc.valid = false; // initialize as invalid
    cc.type = AEX; // initialize at american express

    bool valid;

    char s[20];
    sprintf( s, "%d", n ); // convert credit card number into char array
    printf("%s\n", s);
    return cc;
}

The following snippet does not work,

以下代码段不起作用,

CreditCard validate_card(long long n) {

    CreditCard cc; // specify new credit card
    cc.n = n; // specify card num as passed
    cc.valid = false; // initialize as invalid
    cc.type = AEX; // initialize at american express

    bool valid;

    char s[20];
    sprintf( s, "%d", n ); // convert credit card number into char array
    printf("%s\n", s[0]);
    return cc;
}

On that note, if anyone could also too explain to me how to concatinate char array elements to char pointers, I'd be grateful.

关于这一点,如果有人也能向我解释如何将 char 数组元素连接到 char 指针,我将不胜感激。

回答by R Sahu

When you use this line.

当你使用这条线时。

printf("%s\n", s[0]);

The compiler should print some warning about mismatch of the format string %sand the corresponding argument, s[0].

编译器应该打印一些关于格式字符串%s和相应参数不匹配的警告,s[0].

The type of s[0]is char, not char*.

的类型s[0]char,不是char*

What's your intention?

你的意图是什么?

If you want to print just one character, use:

如果只想打印一个字符,请使用:

printf("%c\n", s[0]);

If you want to print the entire array of chracters, use:

如果要打印整个字符数组,请使用:

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

回答by Mohit Jain

You need to replace below line

您需要替换以下行

printf("%s\n", s[0]);

with

printf("%c\n", s[0]);

to print 1 character.

打印 1 个字符。

To print all characters 1 by 1, use a loop.

要一个一个地打印所有字符,请使用循环。

回答by Edward Clements

If you need to print only the first character of the array, you need to use %c, like

如果您只需要打印数组的第一个字符,则需要使用%c,例如

printf("%c\n", s[0]);

Take a look at this MSDN reference

看看这个 MSDN 参考