如何从 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/