[英]Output array as a "String" separated by commas in c
I have the following array:我有以下数组:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main () {
int openedLockers[5] = {0,1,2,3,4};
return 0;
}
And would like to output "Opened Lockers: 0,1,2,3,4."并想output“打开储物柜:0,1,2,3,4”。
It specifically has to end with a period after the last number.它特别必须以最后一个数字之后的句点结束。 I'm not sure how to do this in a for loop in a way that I do not have to print the "Opened Lockers: " part more than once.我不确定如何以不必多次打印“打开的储物柜:”部分的方式在 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.
A super easy way to achieve the desired format is to use a conditional (ternary) operator as part of your printf
format string within the output loop, eg实现所需格式的超级简单方法是在 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;
}
Example Use/Output示例使用/输出
$ ./bin/openlockers
Opened Lockers: 0,1,2,3,4.
Look things over and let me know if you have further questions.检查一下,如果您还有其他问题,请告诉我。
To do that without branches:要在没有分支的情况下做到这一点:
#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.");
}
Loop only the repeated part to avoid if
s or other conditional constructs.只循环重复的部分以避免if
或其他条件结构。 Note that the repeated part repeats one less time than the number of elements.注意,重复部分重复次数比元素个数少一次。
// 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.