简体   繁体   English

逐行读取文件并将字符串拆分为c中的标记

[英]Reading a file line by line and splitting the string into tokens in c

I am reading a file line by line and splitting the string into tokens. 我正在逐行读取文件并将字符串拆分为令牌。

int main()
{
    FILE* fp;
    char  line[255];

    fp = fopen("file.txt" , "r");
    while (fgets(line, sizeof(line), fp) != NULL)
    {   
        char val1[16];
        char val2[9];

        strcpy(val1, strtok(line, ","));
        strcpy(val2, strtok(NULL, ","));

        printf("%s|%s\n", val1, val2);          
    }
}

My input file content (file.txt) 我的输入文件内容(file.txt)

182930101222, KLA1512
182930101223, KLA1513
182930101224, KLA1514
182930101225, KLA1515

When I print get 当我打印时得到

 | KLA1512

Instead of 代替

182930101222| KLA1512

What is the issue ? 有什么问题?

Your problem (again) is that you're not allocating enough space for an array, and overwriting the end of it. 您的问题(再次)是您没有为数组分配足够的空间,而是覆盖了数组的末尾。 The irony is that in this case, you don't even need to allocate any (additional) arrays. 具有讽刺意味的是,在这种情况下,您甚至不需要分配任何(其他)数组。 strtok() is tokenizing the line[] array, overwriting the delimiters with '\\0' chars, and those are sufficient for your needs. strtok()正在标记line[]数组,并用'\\0'字符覆盖定界符,这些足以满足您的需求。

int main()
{
    FILE* fp;
    char  line[255];

    fp = fopen("file.txt" , "r");
    while (fgets(line, sizeof(line), fp) != NULL)
    {
        const char* val1 = strtok(line, ",");
        const char* val2 = strtok(NULL, ",");

        printf("%s|%s\n", val1, val2);
    }
}

fgets inserts a newline fgets插入换行符

simply increase val2 size by 1 ie val2[10] 只需将val2大小增加1即val2[10]

or remove trailing '\\n' 或删除结尾的'\\n'

while( fgets(line, sizeof(line), fp) != NULL ){ 
        char val1[16] ,val2[9];
        char *pos;
        if ((pos=strchr(line, '\n')) != NULL)
            *pos = '\0';
        strcpy(val1 , strtok(line,","));
        strcpy(val2 , strtok(NULL,","));
        printf("%s|%s\n",val1, val2);           
}

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

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