[英]Extract 2nd and 3rd value from char array and cast it as short (2 bytes). In C
[英]C - 3rd scanf modifies a variable from 2nd scanf
我想我已經嘗試了任何方法(刷新標准輸入,使用scanf消耗換行符等),但是沒有任何工作如我所希望的那樣。 由於某些原因,第三個scanf在以下代碼中修改了第二個scanf中的變量:
#include <stdio.h>
int main()
{
char first_name[16], last_name[21];
char filename[11];
FILE *opening;
printf("The program saves your first and last name into a file.\n");
printf("Enter your first name:");
scanf("%s", first_name);
getchar();
printf("Enter your last name:");
scanf(" %s", last_name);
getchar();
printf("File where you want to save your name:");
scanf(" %s", filename);
opening = fopen(filename, "wb");
fprintf(opening, "%s %s", first_name, last_name);
printf("\nSuccessfully saved the data!");
fclose(opening);
return 0;
}
輸出:
The program saves your first and last name into a file.
Enter your first name: John
Enter your last name: Doe
File where you want to save your name: filename.txt
Successfully saved the data!
一切正常,但文件名.txt的內容是這樣的:
約翰
我猜想't'字符以某種方式來自'txt',但是我剛開始學習C語言,我不知道如何解決這段代碼。 上師可以幫我嗎?
您的filename
緩沖區太小。
您編寫filename.txt
,它是12個字符,再加上零以完成它,使結果為13。您只分配了11。請嘗試如下操作:
char filename[20];
它應該工作。
使用scanf
要小心,因為它可能會導致非常討厭的問題,就像您現在遇到的那樣。 實驗和學習C語言非常有用,因為它向您展示了正確的內存處理的重要性。 對於任何實際項目,您應該考慮使用不同的功能或框架。
如果要輸入filename.txt作為文件名,那么您將超出緩沖區的filename
。 這是未定義的行為 ,是導致奇怪結果的原因。
要解決,將char filename[11];
較大,記住要為NULL終止符再增加1個字符。 在您的特定情況下,應為char filename[14];
在scanf
呼叫中的%s
之前留出錯誤的空間。
否則,一切看起來都很好。
在字符串上使用scanf()
很危險,因為與緩沖區提供的內存相比 , 它可能將更多的數據讀入緩沖區 。
如果以字符串掃描,則應始終通過將這個數字添加到傳遞給scanf()
的格式中,來告訴scanf()
讀取多少個字符:
char file_name[11];
...
scanf("%10s", file_name); /* As file_name provides memor for 11 characters, read a
maximum of 10 characters into file_name leaving 1
character room for the necessary `0-`terminator indicating
the end of the "string". */
同樣,您的代碼也缺少對fopen
系統調用的錯誤檢查。
最好做這樣的事情:
opening = fopen(filename, "wb");
if (NULL == opening)
{
perror("fopen() failed");
exit(EXIT_FAILURE);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.