简体   繁体   English

在C中有多个分隔符的scanf

[英]scanf with more than one delimiter in C

I have a data file with strings, floats, and integers separated by a single comma and a random number of spaces. 我有一个数据文件,其中的字符串,浮点数和整数由单个逗号和随机数的空格分隔。 for example: 例如:

john    , smith ,  3.87 ,  2,  6

I would like to scan each value into a struct containing str,str,float,int,int & ignore the commas and spaces. 我想将每个值扫描到包含str,str,float,int,int的结构中,并忽略逗号和空格。 I have figured out up to the float but cant seem to get the intgers. 我想通了浮动,但似乎无法获得整数。 any help would be appreciated my code is as follows: 任何帮助将不胜感激我的代码如下:

typedef struct applicant {  
char first[15]; 
char last[15];
float gpa;
int grev;
int greq;
} num1;

int main(int argc, char *argv[])
{
  FILE *in, *out;
  in = fopen(argv[1], "r");
  out = fopen(argv[2], "w");

  num1 class[10];

  int i;

  fscanf(in, "%[^,],%[^,],%f, %d, %d\n", class[i].first, class[i].last, &class[i].gpa, &class[i].grev, &class[i].greq);
  fprintf(out, "%s %s %f %d %d", class[i].first, class[i].last, class[i].gpa, class[i].grev, class[i].greq);

As sturcotte06 mentioned you should use strtok() function alongside with atoi() and atof() to get the expected result. 正如sturcotte06所述,您应该将strtok()函数与atoi()atof()一起使用以获得预期结果。

char text[] = "john    , smith ,  3.87 ,  2,  6";

strcpy(class[i].first, strtok(text, ","));
strcpy(class[i].last, strtok(NULL, ",");
class[i].gpa = atof(strtok(NULL, ","));
class[i].grev = atoi(strtok(NULL, ","));
class[i].greq) = atoi(strtok(NULL, ","));

I suggest the following approach. 我建议采用以下方法。

  1. Read the contents of the file line by line. 逐行读取文件的内容。
  2. I am assuming the white spaces are not relevant. 我假设空白不相关。 If that is indeed the case, replace the comma characters with spaces. 如果确实如此,请用空格替换逗号。
  3. Use a simpler format to read the data from the line of text to your struct. 使用更简单的格式从文本行到结构读取数据。

Always check the return value of functions that read data from an input stream to make sure that you use the data only if the read operation was successful. 始终检查从输入流读取数据的函数的返回值,以确保仅在读取操作成功的情况下才使用数据。


// Make it big enough for your needs.
#define LINE_SIZE 200

char line[LINE_SIZE];
if ( fgets(line, LINE_SIZE, in) != NULL )
{
   // Replace the commas by white space.
   char* cp = line;
   for ( ; *cp != '\0'; ++cp )
   {
      if ( *cp == ',' )
      {
         *cp = ' ';
      }
   }

   // Now use sscanf to read the data.
   // Always provide width with %s to prevent buffer overflow.
   int n = sscanf(line, "%14s%14s%f%d%d",
                  class[i].first,
                  class[i].last,
                  &class[i].gpa,
                  &class[i].grev,
                  &class[i].greq);

   // Use the data only if sscanf is successful.
   if ( n == 5 )
   {
      // Use the data
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM