【问题标题】:Reading C Input with skipping commas and columns使用跳过逗号和列读取 C 输入
【发布时间】:2016-02-13 06:43:30
【问题描述】:

我是 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)

现在,我想将 k1、k2、k3 等保存在数组键 [10] 中,并将 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);

 }

【问题讨论】:

    标签: c input filereader scanf file-read


    【解决方案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
    

    【讨论】:

    • 哇!非常感谢你的帮助。但是我在这里有一个小问题:所以这里的 %31 (或您想要的任何数字)正在读取字符值?所以这意味着我可以将 31 更改为我想要的任何数字,对吗?还有,[^,]中的值,这意味着它在一个符号中跳过“”和“,是吗?
    • @KevinYan %31 必须比数组的大小小一,以避免缓冲区溢出。例如,由于我使用数组声明 keys[10][32] 为每个字符串保留了 32 个字节,那么我需要告诉 scanf 不要写入超过 31 个字节,加上空终止符。您可以使用任何长度,不必是 32。转换 [^ ,] 表示“读取由任何字符组成的字符串,直到找到空格或逗号”。
    • @ChristopherSchneider 因为正则表达式不是 C 语言的一部分。欢迎您发布自己的答案,推荐和演示在 C 程序中提供正则表达式功能的库的使用。
    • 不知道这一点。 ANSI C 中没有任何内容,但 POSIX 中有正则表达式,所以我想这很常见。 man7.org/linux/man-pages/man3/regcomp.3.html 没有正则表达式的世界不是我想要生活的地方。
    • “我想这很常见。” 值得怀疑的是,fscanf 是一行代码,你建议用多少行(模糊,非-便携式)代码?
    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 2013-02-12
    • 2013-10-29
    • 2017-10-05
    • 2019-05-11
    • 1970-01-01
    相关资源
    最近更新 更多