如何将用户输入的逗号分隔10个数字存入C语言数组?
Fixing Comma-Separated Number Input for Your Array
Hey there! Let's break down what's going wrong with your current code and fix it so you can properly read 10 comma-separated numbers into your array.
First, let's spot the issues in your original code:
- Array Out-of-Bounds Error: You're using
&A[10]as the argument forscanf, but your arrayAonly has indices from 0 to 9. AccessingA[10]is undefined behavior—it's memory that doesn't belong to your array. - Only Reads One Number: Your
scanfcall only reads a single integer, and doesn't handle the commas separating the numbers, nor does it loop to read all 10 values.
Solution 1: Simple Loop with scanf (Strict Comma Separation)
If your users will input numbers strictly in the format num1,num2,num3,...num10 (with or without spaces around commas), this straightforward loop will work perfectly:
#include <stdio.h> int main () { int A[10]; // 存储用户输入的数组 printf("Enter your numbers: "); // 读取前9个数字,每个后面跟着逗号 for (int i = 0; i < 9; ++i) { // %d, 表示读取整数后跳过逗号(自动忽略空格) scanf("%d,", &A[i]); } // 读取第10个数字,后面没有逗号 scanf("%d", &A[9]); // 可选:验证输入是否正确存储 printf("\nYour array contains:\n"); for (int i = 0; i < 10; ++i) { printf("%d ", A[i]); } printf("\n"); return 0; }
How this works:
- The format specifier
%d,tellsscanfto read an integer, then skip over the following comma (it also automatically ignores any whitespace around the comma, so inputs like123 , 456still work). - We handle the 10th number separately since it won't have a trailing comma.
Solution 2: Robust Line Reading with String Parsing
If you want to handle more flexible input (like extra spaces, accidental newlines, or partial input), reading the entire line first and then parsing it is a better approach. Here's how to do that with fgets and strtok:
#include <stdio.h> #include <string.h> #include <stdlib.h> int main () { int A[10]; char input_buffer[200]; // 足够容纳输入的缓冲区 printf("Enter your numbers: "); // 读取整行输入(包括所有逗号和空格) if (fgets(input_buffer, sizeof(input_buffer), stdin) == NULL) { printf("Error reading input!\n"); return 1; } // 使用strtok分割输入,逗号、空格、换行符都作为分隔符 char* token = strtok(input_buffer, ", \n"); int count = 0; while (token != NULL && count < 10) { // 将分割后的字符串转为整数 A[count] = atoi(token); // 获取下一个分割后的片段 token = strtok(NULL, ", \n"); count++; } // 检查是否读取了足够的数字 if (count < 10) { printf("Warning: Only %d numbers were entered (expected 10).\n", count); } // 验证输出 printf("\nYour array contains:\n"); for (int i = 0; i < count; ++i) { printf("%d ", A[i]); } printf("\n"); return 0; }
Why this is better:
fgetscaptures the entire input line, avoiding issues with leftover newline characters fromscanf.strtoksplits the input on commas, spaces, and newlines, so messy inputs like123 ,456 , 789\nare handled correctly.- We add a check to warn if fewer than 10 numbers were entered, making the code more user-friendly.
内容的提问来源于stack exchange,提问作者user9741196
相关产品推荐
相关产品推荐

