【问题标题】:How to read input from stdin until EOF read line by line with each line containing four space separated integers in C如何从标准输入读取输入,直到 EOF 逐行读取,每行包含 C 中的四个空格分隔的整数
【发布时间】:2015-06-02 08:37:15
【问题描述】:

如何从标准输入读取输入,直到 EOF 逐行读取,每行包含四个空格分隔的 C 中的整数。可以通过如下命令输入:

$ 回声 1 2 3 4 | ./myProgram

$ cat file.txt
1 2 3 4
0 -3 2 -4

$ ./myProgram “这是输出我的计算的地方”

然后我想将单个整数保存到 int 变量中。

char strCoordinates[101];
    char *ptr;
    int coordinates[4];
    long int tempCoordinates;
    while(scanf("%s", strCoordinates) != EOF) {
        tempCoordinates = strtol(strCoordinates, &ptr, 10);
        int lastDigit = 0;
        for (int x = 4; x >= 4; x--) {
            lastDigit = tempCoordinates % 10;
            coordinates[x] = lastDigit;
            tempCoordinates = (tempCoordinates - lastDigit) / 10;
            }
    }

这是我正在尝试的,但它似乎很复杂。 . .

任何帮助将不胜感激。不确定是否使用scanf()sscanf()fscanf()gets()

【问题讨论】:

  • scanf("%s", strCoordinates) 不是“read line by line”。
  • while(scanf("%100[^\n]%*c", strCoordinates) != EOF)@BLUEPIXY 怎么样

标签: c unix input stdin eof


【解决方案1】:

一种方式的例子

char strCoordinates[101];
char *ptr;
int coordinates[4];
while(fgets(strCoordinates, sizeof(strCoordinates), stdin) != NULL) {
    char *s = strCoordinates;
    for (int x = 0; x < 4; x++) {
        coordinates[x] = strtol(s, &ptr, 10);
        s = ptr;
    }
    printf("%d,%d,%d,%d\n", coordinates[0],coordinates[1],coordinates[2],coordinates[3]);
}

【讨论】:

  • 为什么使用&amp;ptr 而不是&amp;s?如果你确实想要ptr,为什么不把它放在for 循环的本地呢?
  • @Paul 1) 可能不是问题,但两个指针是restrictlong strtol( const char * restrict nptr, char ** restrict endptr, int base);。 2) 意义不大。因为它是部分代码对其他的影响很小的就是定义最近使用的一个我已经添加的变量。
  • 那些限制只是说 nptr 和 endptr 不指向同一个数组。因为 &s 绝对不在与字符串 s 指向的相同数组中,所以即使你传递 &s 也没关系
猜你喜欢
  • 2018-04-28
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
  • 2014-04-09
相关资源
最近更新 更多