c - 如何从标准输入读取输入,直到 EOF 逐行读取,每行包含 C 中的四个空格分隔的整数

标签 c unix input stdin eof

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

$ 回声 1 2 3 4 | ./我的程序

$猫文件.txt
1 2 3 4
0 -3 2 -4

$ ./myProgram < 文件.txt
“这是它输出我的计算结果的地方”

然后我想将单个整数保存到 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()

最佳答案

一种方式的例子

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]);
}

关于c - 如何从标准输入读取输入,直到 EOF 逐行读取,每行包含 C 中的四个空格分隔的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29327417/

相关文章:

c - 关系 T(n)=nT(n-1)+n 的时间复杂度是多少

c - xv6操作系统——三重间接的实现

c - C语言中如何复制到数组?

c - 如何检测或测试用于 USB 闪存驱动器插入的 unix/linux 开发节点创建

c# - GetLastInputInfo 是用户特定的 - 是否有类似的东西可以提供机器范围的最后输入时间

javascript - 使用 JavaScript 将输入发送到 url 并控制 iframe 直到提交?

c - 如何将参数分配给字符串数组?

Bash:使用第 n 行作为命令行的一部分

linux - 如何使用cp linux将同名文件从多个目录复制到新目录

python - PyQt5 和 Python 中的用户输入验证