我正在尝试从文件中读取数字并将这些数字放入数组中。现在文件看起来像这样:
100
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
显然,第一个数字是数组的大小。当我尝试测试阅读时,我得到了8。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * filePtr;
int firstNum;
filePtr = fopen("array,dat", "r");
if(filePtr!=NULL)
{
fscanf(filePtr, "%d", &firstNum);
fclose(filePtr);
}
printf("size: %d", firstNum);
return 0;
}
这是我得到的结果:
size: 8
Process returned 0 (0x0) execution time : 0.012 s
Press any key to continue.
那么我怎样才能得到我想要的正确数字以及它为什么显示8?
答案 0 :(得分:4)
由于拼写错误array,dat
- &gt; array.dat
,您的程序无法打开该文件。因此,它只会打印未初始化的变量firstNum
的内容,其中可能包含任何垃圾值。
如果您编写错误处理会更好,例如:
if(filePtr==NULL)
{
printf("Could not open file %s", fileName);
return 0; // no point in continuing execution after this
}
答案 1 :(得分:0)
试试这个
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *myFile;
myFile = fopen("array.dat", "r");
//read file into array
int numberArray[100];
int i;
if (myFile == NULL)
{
printf("Error Reading File\n");
exit (0);
}else
{
for (i = 0; i < (sizeof( numberArray ) / sizeof( numberArray[0] )); i++)
{
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < (sizeof( numberArray ) / sizeof( numberArray[0] )); i++)
{
printf("Number is: %d\n\n", numberArray[i]);
}
}
fclose(myFile);
return 0;
}
答案 2 :(得分:0)
有很多方法可以完成这项任务。关键是使其无论输入格式的微小变化如何都能正常工作。这就是strtol
擅长的地方。它还提供了比大多数转换失败更好的错误分析。
下面的示例只是通过一次读取一行并将该行解析为strtol
的值,将数据读入数组。看一看,试一试。 注意以下处理分配内存的函数只是为了保持代码的主体清洁,这样你就可以更容易地遵循逻辑,而不需要所有的分配验证检查填满main()
。祝你好运:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#define ROWS 3
#define COLS 3
#define MAXC 256
long xstrtol (char *p, char **ep, int base);
void *xcalloc (size_t n, size_t s);
void *xrealloc_sp (void *p, size_t sz, size_t *n);
void *xrealloc_dp (void **p, size_t *n);
int main (void) {
char line[MAXC] = {0}; /* line buffer for fgets */
char *p, *ep; /* pointers for strtol */
int **array = NULL; /* array of values */
size_t row = 0, col = 0, nrows = 0; /* indexes, number of rows */
size_t rmax = ROWS, cmax = COLS; /* row/col allocation size */
/* allocate ROWS number of pointers to array of int */
array = xcalloc (ROWS, sizeof *array);
/* read each line in file */
while (fgets(line, MAXC, stdin))
{
p = ep = line; /* initize pointer/end pointer */
col = 1; /* start col at 1, store ncols in 0 */
cmax = COLS; /* reset cmax for each row */
/* allocate COLS number of int for each row */
array[row] = xcalloc (COLS, sizeof **array);
/* convert each string of digits to number */
while (errno == 0)
{
array[row][col++] = (int)xstrtol (p, &ep, 10);
if (col == cmax) /* if cmax reached, realloc array[row] */
array[row] = xrealloc_sp (array[row], sizeof *array[row], &cmax);
/* skip delimiters/move pointer to next digit */
while (*ep && *ep != '-' && (*ep < '0' || *ep > '9')) ep++;
if (*ep)
p = ep;
else /* break if end of string */
break;
}
array[row++][0] = col; /* store ncols in array[row][0] */
/* realloc rows if needed */
if (row == rmax) array = xrealloc_dp ((void **)array, &rmax);
}
nrows = row; /* set nrows to final number of rows */
printf ("\n the simulated 2D array elements are:\n\n");
for (row = 0; row < nrows; row++) {
for (col = 1; col < (size_t)array[row][0]; col++)
printf (" %4d", array[row][col]);
putchar ('\n');
}
putchar ('\n');
/* free all allocated memory */
for (row = 0; row < nrows; row++)
free (array[row]);
free (array);
return 0;
}
/** a simple strtol implementation with error checking.
* any failed conversion will cause program exit. Adjust
* response to failed conversion as required.
*/
long xstrtol (char *p, char **ep, int base)
{
errno = 0;
long tmp = strtol (p, ep, base);
/* Check for various possible errors */
if ((errno == ERANGE && (tmp == LONG_MIN || tmp == LONG_MAX)) ||
(errno != 0 && tmp == 0)) {
perror ("strtol");
exit (EXIT_FAILURE);
}
if (*ep == p) {
fprintf (stderr, "No digits were found\n");
exit (EXIT_FAILURE);
}
return tmp;
}
/** xcalloc allocates memory using calloc and validates the return.
* xcalloc allocates memory and reports an error if the value is
* null, returning a memory address only if the value is nonzero
* freeing the caller of validating within the body of code.
*/
void *xcalloc (size_t n, size_t s)
{
register void *memptr = calloc (n, s);
if (memptr == 0)
{
fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
exit (EXIT_FAILURE);
}
return memptr;
}
/** reallocate array of type size 'sz', to 2 * 'n'.
* accepts any pointer p, with current allocation 'n',
* with the type size 'sz' and reallocates memory to
* 2 * 'n', updating the value of 'n' and returning a
* pointer to the newly allocated block of memory on
* success, exits otherwise. all new memory is
* initialized to '0' with memset.
*/
void *xrealloc_sp (void *p, size_t sz, size_t *n)
{
void *tmp = realloc (p, 2 * *n * sz);
#ifdef DEBUG
printf ("\n reallocating '%zu' to '%zu', size '%zu'\n", *n, *n * 2, sz);
#endif
if (!tmp) {
fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
exit (EXIT_FAILURE);
}
p = tmp;
memset (p + *n * sz, 0, *n * sz); /* zero new memory */
*n *= 2;
return p;
}
/** reallocate memory for array of pointers to 2 * 'n'.
* accepts any pointer 'p', with current allocation of,
* 'n' pointers and reallocates to 2 * 'n' pointers
* intializing the new pointers to NULL and returning
* a pointer to the newly allocated block of memory on
* success, exits otherwise.
*/
void *xrealloc_dp (void **p, size_t *n)
{
void *tmp = realloc (p, 2 * *n * sizeof tmp);
#ifdef DEBUG
printf ("\n reallocating %zu to %zu\n", *n, *n * 2);
#endif
if (!tmp) {
fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
exit (EXIT_FAILURE);
}
p = tmp;
memset (p + *n, 0, *n * sizeof tmp); /* set new pointers NULL */
*n *= 2;
return p;
}
<强>编译强>
gcc -Wall -Wextra -Ofast -o bin/array_ukn_size array_ukn_size.c
<强>输入强>
$ cat ../dat/10by10.txt
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
<强>输出强>
$ ./bin/array_ukn_size <../dat/10by10.txt
the simulated 2D array elements are:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
答案 3 :(得分:0)
例如,您的输入文件名是 input.txt 。现在将此文件与源(.c)文件保存在同一文件夹中。 现在您可以通过这种方式读取输入文件
freopen("input.txt","r",stdin);
这里是完整的代码
#include <stdio.h>
int main()
{
int firstNum,otherNum;
freopen("input.txt","r",stdin);
scanf("%d",&firstNum);// this read first number 100
while(scanf("%d",&otherNum)==1)// this loop continue until end of file
{
// hear you get other numbers
printf("%d",otherNum) ; // this line print 0 1 2 3 to 99
}
return 0;
}
注意:使用代码::块 IDE