![](/img/trans.png)
[英]How to read string with spaces, integers and float values from a file in c?
[英]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();
}
我的文件包含帶空格的字符串,當我從文件中讀取一行時,該行僅包含第一個單詞,而忽略空格后的字符串。
是的,因為sscanf()
(以及所有scanf()
函數)都使用%s
說明符來讀取直到第一個空格字符的字符串。 因此,您可以通過該調用明確截斷行。 在我看來,您想處理整行,因此sscanf沒用-刪除它。
您需要使用EOF語句來完全讀取文件,例如,在您的情況下:
while ((line = getc(fin)) != EOF)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.