[英]Why is the C program giving weird output using Scanf?
我目前正在學習 C 編程,我遇到了這個奇怪的 output。
// Program will try functionalities of the scanf function
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char const *argv[])
{
char array[40];
scanf("Enter your address: %39s",array); //39 + 1/o null character at the end of the character array.
printf("The address is : %s", array);
return 0;
}
它應該接受輸入地址和 output 相同。
PS C:\Users\G\Documents\C programs> gcc scanff.c -o scanff -Wall -pedantic -std=c99
PS C:\Users\G\Documents\C programs> ./scanff
jhgjhg
The address is : ■ a
那個黑塊是什么? 有人可以解釋一下。 謝謝。
只需為scanf()
function 正確使用格式說明符並使用printf()
顯示自定義消息。
看看下面的代碼:
// Program will try functionalities of the scanf function
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char const *argv[])
{
char array[40];
printf("Enter your address: ");
scanf("%39s",array); //39 + 1/o null character at the end of the character array.
printf("The address is : %s", array);
return 0;
}
您應該再次查看 scanf 的文檔。 格式字符串應包含格式規范和要按字面匹配的非格式字符。 您似乎認為可以使用scanf()
進行提示,這是不正確的。
使用此(未經測試的)代碼,您可能會取得更大的成功:
int main(int argc, char const *argv[])
{
char array[40];
printf("Enter your address: ");
scanf("%39s",array); //39 + 1/o null character at the end of the character array.
printf("The address is : %s\n", array);
return 0;
}
檢查scanf()
調用的結果以查看是否讀取了預期數量的值也是一種很好的做法。 在您的情況下,該值可能為 0,因為您的輸入中的文字字符不匹配。 當不使用格式規范時,目標變量的值不變(在這種情況下未定義,因為數組包含恰好位於分配變量的堆棧上的字節。)
兩個問題:
您沒有正確初始化array
。 它應該是:
char array[40] = "";
您將 scanf 和 printf 與以下語句混合在一起:
scanf("Enter your address: %39s",array);
它應該分為:
printf( "Enter your address: " );
scanf ("%39s", array);
從scanf的手冊頁:
int scanf(const char *format, ...);
未定義 output 的原因:
format
中的每個轉換規范都以字符“%”或字符序列“%n$”開頭
解決方法:更改scanf("Enter your address: %39s",array);
到scanf("%39s",array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.