我得到了带有信息的文本文件:(100;200;first)。谁能告诉我如何将此信息分成三个数组:Min=100,Max=200 和 Name=first。我试过这个
c=getc(inp);
i=atoi(szinput);
但它第一次读取 10,第二次读取 00 ......等等循环
c 保存 10 而不是 1,所以我无法获得正确的数组信息...
所以数组 Min 存储 1000 而不是 100
谢谢。
使用scanf
或fscanf
像这样:
scanf("(%d;%d;%[^)])",&min,&max,str);
您可以执行以下操作
FILE *file;
char readBuffer[40];
int c;
file = fopen("your_file","r");
while ((c=getc(file))!= EOF)
{
strcat(readBuffer, c);
if( (char) c == ';')
//this is the delimiter. Your min, max, name code goes here
}
fclose(file);
使用strtok()
:
#include <stdio.h>
#include <string.h>
int main() {
char input[] = "100;200;first";
char name[10];
int min, max;
char* result = NULL;
char delims[] = ";";
result = strtok(input, delims);
// atoi() converts ascii to integer.
min = atoi(result);
result = strtok(NULL, delims);
max = atoi(result);
result = strtok(NULL, delims);
strcpy(name, result);
printf("Min=%d, Max=%d, Name=%s\n", min, max, name);
}
输出:
Min=100, Max=200, Name=first