通过跳过逗号和列来读取C输入

时间:2015-11-12 01:36:56

标签: c input filereader scanf file-read

我是C新手,我想做文件读取操作。 这里我有input.txt,其中包含:

(g1,0.95) (g2,0.30) (m3,0.25) (t4,0.12) (s5,0.24)
(m0,0.85) (m1,0.40) (m2,0.25) (m3,0.85) (m4,0.5) (m5,0.10)

现在,我想在数组键[10]中保存k1,k2,k3等,在数组值中保存0.15,0.10,0.05 [10]

有没有办法跳过第一个“(”,忽略“,”和“”没有逐一指定?我试图搜索教程,我听说我可以在它之前和之后阅读几个字符,但是我想我误导了他们。有人能告诉我如何实现这个目标吗?

#include <stdio.h>
#define HEIGHT 2
#define WIDTH  6

int main(void)
{
     FILE *myfile;
     char nothing[100];
     char leaf[2];
     float value;

     char keys[10];
     float values[10];

     int i;
     int j;
     int counter=0;

     myfile=fopen("input.txt", "r");

     for(i = 0; i < HEIGHT; i++)
     { 
         for (j = 0 ; j < WIDTH; j++)
         { 
             fscanf(myfile,"%1[^(],%s[^,],%4f[^)]",nothing,leaf,value);
             printf("(%s,%f)\n",leaf,value);
             keys[counter]=leaf;
             values[counter]=value;
             counter++;
         }
         printf("\n");
     }

     fclose(myfile);

 }

1 个答案:

答案 0 :(得分:1)

这是我将如何做到的:

int main( void )
{
    // open the file
    FILE *fp;
    if ( (fp = fopen("test.txt", "r")) == NULL )
        exit( 1 );

    // declare the arrays
    char keys[10][32];
    float values[10];

    // load them up
    int i;
    for ( i = 0; i < 10; i++ )
        if ( fscanf( fp, " ( %31[^ ,] ,%f )", keys[i], &values[i] ) != 2 )
            break;
    int count = i;

    // print them out
    printf( "%d\n", count );
    for ( i = 0; i < count; i++ )
        printf( "%s %.2f\n", keys[i], values[i] );

    // close the file
    fclose( fp );
}

密钥是scanf的格式说明符,由5个元素组成。 请注意,我使用下划线来显示空格的位置

_(_      skips whitespace, matches the opening parenthesis, skips whitespace
%31[^_,] reads at most 31 characters, stopping on a space or a comma
_,       skips whitespace, matches the comma
%f       reads a floating point value
_)       skips whitespace, matches the closing parenthesis