从字符串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;
}
OUTPUT:
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
}
请学习如何创建一个[最小,完整,可验证的例子](htt号码://stackoverflow.com/help/mcve)。即一个我们可以复制和构建的程序,它演示了你所尝试过的东西。还包括* exact *输入,最好是预格式化(或代码格式)文本的会话,显示确切的输入和实际(以及预期)输出。 –
我建议你在C中查找字符串格式。仅在SO上有大量的例子。 – StoryTeller
试试这个https://stackoverflow.com/questions/4513316/split-string-in-c-every-white-space –