我正在嘗試創建一個程式來輸出不超過 5 個字符的名字。
#include <stdio.h>
#include <stdlib.h>
int main()
{
//declaring fisrtname
char firstname[5];
printf("Enter your name: ");
scanf("%s", &firstname);
printf("\nYour name: %s", firstname);
return 0;
}
在運行程式時,我在命令提示符中得到了這個:
Enter your name: newton
Your name: ←
Process returned 0 (0x0) execution time : 4.719 s
Press any key to continue.
uj5u.com熱心網友回復:
有幾個錯誤阻礙了你:
- 傳遞給 scanf 的引數型別錯誤(您正在傳遞一個指向陣列的指標,但它只是期望一個指標)。我會將該行更改為:
scanf("%s", firstname);
- scanf 函式會很高興地溢位您的檔案名 [5] 緩沖區。快速解決方法是將緩沖區的大小增加到 256 之類的大小。但是要以正確的方式做到這一點,您需要切換到使用
fgets(傳入標準輸入)之類的東西。 - 要將名稱截斷為五個字符,您需要將 '\0'(空終止符)寫入緩沖區中的第六個記憶體位置(再次確保緩沖區足夠大)。
filename[5] = '\0';
這是您的代碼的作業版本:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//declaring fisrtname
char firstname[256];
printf("Enter your name: ");
scanf("%s", firstname);
firstname[5] ='\0';
printf("\nYour name: %s", firstname);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322571.html
標籤:C
上一篇:關于指標在C中如何作業的問題
