簡體   English   中英

Output 數組作為“字符串”,在 c 中用逗號分隔

[英]Output array as a "String" separated by commas in c

我有以下數組:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main () {

int openedLockers[5] = {0,1,2,3,4};


return 0;
}

並想output“打開儲物櫃:0,1,2,3,4”。

它特別必須以最后一個數字之后的句點結束。 我不確定如何以不必多次打印“打開的儲物櫃:”部分的方式在 for 循環中執行此操作。

#include <stdio.h>

int main () {

int openedLockers[] = {0,1,2,3,4};

printf("Opened Lockers: ");

for (size_t i = 0; i < 5; i++) {
    printf("%d", openedLockers[i]);

    if (i != 4)
        printf(",");
    else
        printf(".");
}
return 0;
}


// Output : Opened Lockers: 0,1,2,3,4.

實現所需格式的超級簡單方法是在 output 循環中使用條件(三元)運算符作為printf格式字符串的一部分,例如

#include <stdio.h>

int main (void) {

    int openedLockers[] = {0,1,2,3,4},
        n = sizeof openedLockers / sizeof *openedLockers;

    fputs ("Opened Lockers: ", stdout);

    for (int i = 0; i < n; i++)
        printf (i ? ",%d" : "%d", openedLockers[i]);
    puts (".");

    return 0;
}

示例使用/輸出

$ ./bin/openlockers
Opened Lockers: 0,1,2,3,4.

檢查一下,如果您還有其他問題,請告訴我。

要在沒有分支的情況下做到這一點:

#include <stddef.h>
#include <stdio.h>

int main (void)
{
    int openedLockers[] = {0, 1, 2, 3, 4};
    size_t const n = sizeof openedLockers / sizeof *openedLockers;

    printf("Opened Lockers: ");

    for (size_t i = 0; i < n; ++i)
        printf("%d,", openedLockers[i]);

    puts("\b."); // overwrite the last comma with a period and add a newline.
}
#include <stddef.h>
#include <stdio.h>

int main (void)
{
    int openedLockers[] = {0, 1, 2, 3, 4};
    int const n = sizeof openedLockers / sizeof *openedLockers;

    printf("Opened Lockers: ");

    for (int i = 0; i < n; ++i)
        printf("%d,", openedLockers[i]);

    printf("\b.");
}

只循環重復的部分以避免if或其他條件結構。 注意,重復部分重復次數比元素個數少一次。

// before repeats, include first element
printf("Opened Lockers: %d", openedLockers[0]);

// repeat comma, space, element
for (int i = 1; i < 5; i++) {
    printf(", %d", openedLockers[i]);
}

// after repeats
printf(".\n");
#include <stdio.h>

void print_array(int *a, int n);
int main(void)
{
    int array[5];

    array[0] = 98;
    array[1] = 402;
    array[2] = -198;
    array[3] = 298;
    array[4] = -1024;
    print_array(array, 5);
    return 0;
}
void print_array(int *a, int n){
    int i = 0;
    for (i = 0; i <= n - 1; i++){
        printf("%d ,",a[i]);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM