1

我有一个问题,我试图研究它,但无法真正找到我正在寻找的答案。

我试图在 C 中以这种方式接收多行文本文件

./{base_name} < input.txt

input.txt 包含

54
37
100
123
1
54

我已经得到了它的工作方式

scanf("%[^\t]",s);

但我想获取每个数字并将 C 字符串解析为整数数组,可能使用 atoi()。我很不确定该怎么做。

现在我的代码看起来像这样

int main(int argc, char *argv[]){
   char str[1000];
   scanf("%[^\t]",str);
   printf("%s\n", str);
}

有没有办法使用 argc 和 **argv 来做到这一点,或者另一种巧妙的方式来获取输入并制作一个 int 数组。

我正在编译:

gcc -w --std=gnu99 -O3 -o {base_name} {file_name}.c -lm

最好的办法就是将其作为 .txt 文件并使用 fopen 等,但作业要求我将输入作为 ./{base_name} < input.txt

我有一个有效的答案。除此之外,我还有这段代码也很好用。但是会推荐接受的答案,因为它定义了输入中数组的大小。非常感谢你的帮助。

#include <stdio.h>
int main(){
    char s[100];
    int array[100];
    while(scanf("%[^\t]",s)==1){
        printf("%s",s);
    }
    return 0;
}
4

2 回答 2

1

为什么不简单地将输入读取为整数?

//test.c
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[]){
   int n;
   int i;
   int *arr;

   /*Considering first value as number of elements */
   /*Else you can declare an array of fixed size */
   fscanf(stdin,"%d",&n);
   arr = malloc(sizeof(int)*n);

   for(i=0;i<n;i++)
    fscanf(stdin,"%d",&arr[i]);


   for(i=0;i<n;i++)
    printf("%d ",arr[i]);

    free(arr);
    return 0;
}

现在使用:

./test < input.txt

假设 input.txt :

6  <- no. of elements (n)
54
37
100
123
1
54
于 2013-08-26T18:57:31.693 回答
0

你可以试试这段代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv) {
   FILE *file;
   int numbers[100] /* array with the numbers */, i /8 index */, j;

   if (!(file = fopen(argv[1], "r")) return -1; /* open the file name the user inputs as argument for read */

   i = 0; /* first place in the array */
   do /* read the whole file */ {
      fscanf(" %d", &(numbers[i]); /* the space in the format string discards preceding whitespace characters */
      i++; /* next position */
   }

   for (j = 0; j < i; j++) printf("%d", numbers[j]); /* print the array for the user */

   return 0;
}
于 2013-08-26T19:00:26.670 回答