如何使用 fgets 获取第二个整数?
How to get the second integer using fgets?
我希望使用 fgets 获取第二个和第三个整数
用户输入:1 2 3
int firstint, secondint;
char buffer[12];
fgets(firstInteger, 12, stdin);
firstint = atoi(buffer);
printf("%d is the first integer", firstint);
这个的输出是1。
是否可以使用 fgets 获取 2 和 3?
我了解 scanf 会导致问题并希望使用 fgets。
下面的代码从用 ,
.
分隔的字符串 str
中提取数字
它适用于所有非数字分隔符。
函数strtol可能会失败,应该检查一下。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *str = "1, 2, 3";
char *p = str;
char *q;
// While we aren't at the end of string.
while (*p) {
// Convert string number to long
long val = strtol(p, &q, 10);
if (q > p) {
// We've got number, clamped to LONG_MIN..LONG_MAX
// You can store them into array here, if you want.
printf("%ld\n", val);
p = q;
} else {
// Skip character
p++;
}
}
return 0;
}
输出:
1
2
3
您的用例:
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 12
#define NUMBER_COUNT 3
int main(void) {
long numbers[NUMBER_COUNT];
int index = 0;
char buffer[BUFFER_SIZE];
if (fgets(buffer, BUFFER_SIZE, stdin)) {
char *p = buffer;
char *q;
while (*p) {
// Convert string number to long
long val = strtol(p, &q, 10);
if (q > p) {
if (index < NUMBER_COUNT) {
numbers[index++] = val;
} else {
break;
}
p = q;
} else {
// Skip character
p++;
}
}
for (int i = 0; i < index; i++) {
printf("%ld\n", numbers[i]);
}
}
return 0;
}
另一种可能性是提到的scanf
if (scanf("%d %d %d", &var1, &var2, &var3) != 3) {
// Failed to read 3 int's
}
我希望使用 fgets 获取第二个和第三个整数
用户输入:1 2 3
int firstint, secondint;
char buffer[12];
fgets(firstInteger, 12, stdin);
firstint = atoi(buffer);
printf("%d is the first integer", firstint);
这个的输出是1。
是否可以使用 fgets 获取 2 和 3?
我了解 scanf 会导致问题并希望使用 fgets。
下面的代码从用 ,
.
str
中提取数字
它适用于所有非数字分隔符。
函数strtol可能会失败,应该检查一下。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *str = "1, 2, 3";
char *p = str;
char *q;
// While we aren't at the end of string.
while (*p) {
// Convert string number to long
long val = strtol(p, &q, 10);
if (q > p) {
// We've got number, clamped to LONG_MIN..LONG_MAX
// You can store them into array here, if you want.
printf("%ld\n", val);
p = q;
} else {
// Skip character
p++;
}
}
return 0;
}
输出:
1
2
3
您的用例:
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 12
#define NUMBER_COUNT 3
int main(void) {
long numbers[NUMBER_COUNT];
int index = 0;
char buffer[BUFFER_SIZE];
if (fgets(buffer, BUFFER_SIZE, stdin)) {
char *p = buffer;
char *q;
while (*p) {
// Convert string number to long
long val = strtol(p, &q, 10);
if (q > p) {
if (index < NUMBER_COUNT) {
numbers[index++] = val;
} else {
break;
}
p = q;
} else {
// Skip character
p++;
}
}
for (int i = 0; i < index; i++) {
printf("%ld\n", numbers[i]);
}
}
return 0;
}
另一种可能性是提到的scanf
if (scanf("%d %d %d", &var1, &var2, &var3) != 3) {
// Failed to read 3 int's
}