[英]e codeC program to scan string with spaces while in loop [on hold]
int main()
{
char word[50],auth[50],op,w,ch;
int m,i,n,y;
printf("\nEnter Number of Books You Want To Add\n");
scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("BOOK %d\nEnter name : ",i+1);
fgets(word,49,stdin);
printf("Author's Name : ");
scanf("%s",&auth);
printf("Year : ");
scanf("%d",&y);
printf("Catalogue Number : ");
scanf("%d",&m);
printf("\n");
fprintf(fptr,"\tTitle : %s\n\tAuthor : %s\n\tYear : %d\n\tID : %d\n",word,auth,y,m);
printf("\n");
}
fclose(fptr);
printf("\nDone. Yay!\n\n");
return books();
}
我正在編寫一個用於獲取書籍詳細信息的程序,一個數據庫程序,但我無法用空格掃描整個字符串。 scanf()
只掃描第一個字符串,直到它遇到空格。 但是當我使用fgets()
時,程序甚至不允許我在“名稱”部分輸入任何內容。 它只是自動轉到“作者”。
誰能告訴我為什么會這樣以及如何糾正它?
將輸入法與scanf()
和fgets()
混合只會導致麻煩,因為它們處理空格和換行符的方式不同。 scanf()
不讀取最后的換行符,然后fgets
讀取“空字符串”(實際上只是換行符),因為下一個字符是前一個輸入留下的換行符。
要更正它,請使用fgets
輸入所有數據。
對於 integer,然后使用sscanf()
進行提取。 添加了基本的錯誤檢查:
char tempstr[100];
if(fgets(tempstr, sizeof tempstr, stdin) == NULL) {
exit(1); // or other handling
}
if(sscanf(tempstr, "%d", &n) != 1) {
exit(1); // or other handling
}
對於字符串,您需要刪除fgets()
保留的尾隨換行符:
if(fgets(word, sizeof word, stdin) == NULL) {
exit(1); // or other handling
}
word [ strcspn(word, "\n") ] = 0;
另請參閱之前的問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.