我在編程方面相當新,我想嘗試使用檔案指標。我盡了最大的努力試圖找到讓用戶無限輸入字串的方法,并且程式將繼續將它輸入到檔案中。但我仍然無法弄清楚如何。這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char text[100];
FILE *output = fopen("output.txt", "a");
if (output == NULL)
{
printf("Could not open file\n");
return 1;
}
while (1)
{
//Asks the user for input
printf("Enter Text: \n");
scanf("%[^\n]", text);
//if user puts the string "end", it will stop asking for input
if (strcmp(text, "end") != 0)
{
//puts the user input into the file
fprintf(output, "%s\n", text);
}
else
{
break;
}
}
fclose(output);
}
但是在我輸入 1 行字串后,它會一遍又一遍地回圈,直到我手動中斷它。任何幫助,將不勝感激
uj5u.com熱心網友回復:
您的代碼scanf("%[^\n]", text);會讀取所有內容,直到換行符進入緩沖區并將其排除在外。
這對于作為輸入的初始“結束”是成功的。
但這會在輸入中留下一個“\n”,這反過來又會使所有后續輸入無法掃描,因為它們會立即找到終止的“\n”并且它們不會從輸入中洗掉任何內容,甚至沒有洗掉那個“\n”。
假設您可以忽略前導空格,您可以更改為
scanf(" %[^\n]", text);
它將忽略所有前導空格,包括前面行末尾有問題的“\n”。
如果您需要保留前導空白,則需要在知道有一個“\n”時進行更多手術掃描,例如從第二次掃描開始并明確忽略它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/497088.html
上一篇:pandascsvUnicodeDecodeError:'utf-8'codeccan'tdecodebyte0x81inposition162:invalidstart
下一篇:os.walk查找不存在的檔案
