简体   繁体   中英

How to take a string with spaces from a file in C

main()
{
    FILE *fin;
    char line[50];
    char exp[SIZE];
    fin=fopen("prefix.txt","r");

    if(fin==NULL)
    {
         printf("\nFile Cannot be Opened\n");
    }
    else
    {
         printf("\nfile opened\n");

         while(fgets(line, sizeof(line), fin)!=NULL)
         {
              sscanf(line, "%s", exp);
              delete_spaces(exp);
              convert(exp);
         }
    }
    fclose(fin);
    getch();
}

My file is containing string with spaces and when I am reading a line from it, the line is containing only first word and ignoring string after space.

Yeah, because sscanf() (along with all the scanf() functions) uses the %s specifier to read a string up to the first whitespace character. So you explicitly truncate your line with that one call. It seems to me that you want to process the entire line, so that sscanf is just useless -- remove it.

您需要使用EOF语句来完全读取文件,例如,在您的情况下:

while ((line = getc(fin)) != EOF)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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