简体   繁体   English

使用字符串串联在c中打印数组而没有最后一个元素

[英]Print array in c with string concatenation without last element

I am new to C and programming. 我是C和编程新手。 I am trying to print an array separated by comma. 我正在尝试打印用逗号分隔的数组。 But don't wish to print the last comma element. 但是不想打印最后一个逗号元素。 Here is my code so far 到目前为止,这是我的代码

void p_array(const int array[], const int s) {
  for(int i = 0; i < s; i++) {
    printf("%i, ",array[i]);
  }
}

I am getting the array printed as 我正在将数组打印为

1, 2, 3, 4,

Whereas I dont wish to have the last element of comma printed. 而我不希望打印逗号的最后一个元素。 I know I am doing something fundamental wrong. 我知道我在做一些根本性的错误。 Any help is appreciated. 任何帮助表示赞赏。

1, 2, 3, 4
for(int i = 0; i < s; i++) {
  if(i)
    printf(", ");
  printf("%i",array[i]);
}

You could do this: 您可以这样做:

printf("%i%s", array[i], i==s-1 ? "" : ", ");

An alternative is to have the loop go one less iteration, and the print out the last element w/ a printf after the loop. 另一种选择是让循环少进行一次迭代,并在循环后打印出最后一个带有w / printf元素。

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

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