如何实现scanf输入数字后加逗号空格,仅排除最后一个数字?
解决C语言循环输出整数末尾多余逗号的问题
当前使用的代码通过scanf循环读取整数并输出,每次在数字后添加逗号和空格,但最后一个数字后会出现多余的逗号和空格(例如输入5 60 2 6,输出为5, 60, 2, 6,)。以下是几种实用的修改方案:
方案一:先处理第一个输入,后续输入前置分隔符
这种方式直接调整输出顺序,让分隔符出现在数字前面(除了第一个数字),从根源避免末尾多余符号:
#include <stdio.h> int main(int argc, char *argv[]) { int user_input; // 先读取第一个整数,判断是否有有效输入 if (scanf("%d", &user_input) == 1) { printf("%d", user_input); // 读取后续所有整数,先输出分隔符再输出数字 while (scanf("%d", &user_input) == 1) { printf(", %d", user_input); } } // 可选:添加换行让输出更整洁 printf("\n"); return 0; }
方案二:用标志位控制输出格式
通过一个布尔标志位记录是否为第一个输出的数字,灵活调整输出内容:
#include <stdio.h> int main(int argc, char *argv[]) { int user_input; int is_first = 1; // 1表示当前是第一个要输出的数字 while (scanf("%d", &user_input) == 1) { if (is_first) { printf("%d", user_input); is_first = 0; // 输出第一个数后,标志位置0 } else { printf(", %d", user_input); // 非第一个数,先输出分隔符 } } printf("\n"); return 0; }
方案三:先收集所有输入再统一输出
如果需要对输入做额外处理,可先将所有整数存入动态数组,再遍历输出:
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int *nums = NULL; int count = 0; int user_input; // 动态读取所有输入并存储 while (scanf("%d", &user_input) == 1) { count++; nums = realloc(nums, count * sizeof(int)); if (!nums) { perror("内存分配失败"); return 1; } nums[count-1] = user_input; } // 遍历输出,仅在非第一个元素前添加分隔符 for (int i = 0; i < count; i++) { if (i > 0) { printf(", "); } printf("%d", nums[i]); } printf("\n"); free(nums); return 0; }
内容的提问来源于stack exchange,提问作者satoshisakoto
相关产品推荐
相关产品推荐

