【问题标题】:Problems with getting data from multi-line input in the from ./{base} < input.txt从 from ./{base} < input.txt 中的多行输入获取数据的问题
【发布时间】:2013-08-29 08:03:11
【问题描述】:

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

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

./{base_name}

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}

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

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

【问题讨论】:

  • 您的要求要求您从控制台 (stdin) 读取输入。你不应该使用 fopen。代码看起来不错。

标签: c command-line multiline


【解决方案1】:

你可以试试这个代码:

#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;
}

【讨论】:

    【解决方案2】:

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

    //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 &lt; input.txt

    假设 input.txt :

    6  <- no. of elements (n)
    54
    37
    100
    123
    1
    54
    

    【讨论】:

    • 非常感谢您的帮助
    • 不知道发生了什么突然它开始喷涌而出。 37 100 123 1 54 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 相反,而我没有对您的代码进行任何更改。尝试在另一台计算机上编译和运行,结果相同。据我所见,它似乎是第一个数字 54 而不是 6
    • 我似乎无法再打印出第一个元素。 fscanf(stdin,"%d",&n);只给出 54,这是第一个输入
    猜你喜欢
    • 2011-09-04
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多