【发布时间】:2015-07-25 02:01:32
【问题描述】:
我正在编写一个小程序,允许用户输入矩阵的维度m 和n,然后根据自己的喜好填充该矩阵。要读取数字,我使用fgets() 将用户输入读取为字符串,然后通过strtol() 将其转换。我还删除了通过strcspn() 附加的换行符fgets(),并在用户输入a、12a 或只是换行符\n 时进行一些错误处理。但是这个程序让我对通过Ctrl + D 输入的EOF 感到头疼。我阅读了几个关于此的 stackoverflow 线程,我知道在某些情况下需要输入两次EOF。但是,当我将EOF 发送给我第一次调用fgets() 在m-dimension 中读取时,我将被转发到fgets() 的下一个调用中,它读取n-dimensions 并从那里开始跳转到实际的数组输入,它似乎卡住了,或者我进入了一个无限循环。我目前不知道原因,也不知道在这种情况下如何处理EOF。如果有人可以提供一些提示,我会很高兴。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[]) {
/* We use "m_row" and "n_col" to keep track of the matrix dimensions and "m"
* and "n" to keep track of the size of dynamically allocated memory. */
unsigned long int m_row;
unsigned long int n_col;
unsigned long int element;
/* Initializing at dummy value to silence compiler. */
m_row = 1;
n_col = 1;
/* The largest integer that can fit into unsigned long int is a 20-digit
* number. */
char save[20];
char *ptr_save;
printf("Enter number of rows:\n");
if (fgets(save, sizeof(save), stdin) != NULL) {
save[strcspn(save, "\n")] = 0;
if (save[0] == '\0') {
fprintf(stderr, "Wrong input\n");
exit(EXIT_FAILURE);
}
m_row = strtol(save, &ptr_save, 10);
if (*ptr_save != '\0') {
fprintf(stderr, "Wrong input\n");
exit(EXIT_FAILURE);
}
}
printf("Enter number of columns:\n");
if (fgets(save, sizeof(save), stdin) != NULL) {
save[strcspn(save, "\n")] = 0;
if (save[0] == '\0') {
fprintf(stderr, "Wrong input\n");
exit(EXIT_FAILURE);
}
n_col = strtol(save, &ptr_save, 10);
if (*ptr_save != '\0') {
fprintf(stderr, "Wrong input\n");
exit(EXIT_FAILURE);
}
}
errno = 0;
unsigned long int **arr = calloc(m_row, sizeof(unsigned long int *));
if (arr == NULL) {
fprintf(stderr, "%s", strerror(errno));
exit(EXIT_FAILURE);
}
int i;
errno = 0;
for(i = 0; i < m_row; i++) {
arr[i] = calloc(m_row, sizeof(unsigned long int));
if (arr[i] == NULL) {
fprintf(stderr, "%s", strerror(errno));
exit(EXIT_FAILURE);
}
}
int j;
for(i = 0; i < m_row; i++) {
for(j = 0; j < n_col; j++) {
if (fgets(save, sizeof(save), stdin) != NULL) {
save[strcspn(save, "\n")] = 0;
if (save[0] == '\0') {
fprintf(stderr, "Wrong input\n");
exit(EXIT_FAILURE);
}
element = strtol(save, &ptr_save, 10);
if (*ptr_save != '\0') {
fprintf(stderr, "Wrong input\n");
exit(EXIT_FAILURE);
}
arr[i][j] = element;
}
printf("\n");
}
}
for (i = 0; i < m_row; i++) {
for(j = 0; j < n_col; j++) {
printf("%lu\t", arr[i][j]);
}
printf("\n");
}
free(arr);
return 0;
}
【问题讨论】:
标签: c arrays error-handling