how to make arrays from txt file C

こ雲淡風輕ζ 提交于 2019-12-08 05:43:48

问题


I got text file with information: (100;200;first).Can anybody tell me how to seperate this information into three arrays: Min=100,Max=200 and Name=first. I have tried this whith

c=getc(inp);

i=atoi(szinput);

but its read 10 for first time and 00 for second... and so on in loop

c saves 10 not 1, so i cant get the right information for arrays...

So the array Min stores 1000 not 100

Thanks.


回答1:


You could do something like the following

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



回答2:


use scanf or fscanf like this:

scanf("(%d;%d;%[^)])",&min,&max,str);



回答3:


Here is a cool, simple tutorial on how to do that.

Please note that you'll need to adapt the example a little bit, but that should not be too difficult.

Also you could try to find a library that does the job, I'm sure there are a lot of such libraries for C :)




回答4:


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

Output:

Min=100, Max=200, Name=first


来源:https://stackoverflow.com/questions/7785309/how-to-make-arrays-from-txt-file-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!