簡體   English   中英

使用 scanf %c 用垃圾字符填充字符串

[英]Using scanf %c fills string with garbage characters

我將提供一個輸入,output 將與輸入相同。 但是 output 沒有正確顯示。 我在這里給出了代碼以及輸入和 output 例如。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    char s[40];
    scanf("%c", &s);
    printf(s);

    return 0;
}

輸入: love
Output: l Φ■`

為什么會這樣?

由於您正在獲取字符串作為輸入,因此請使用%s格式化程序而不是%c %c只能從標准輸入中獲取單個字符,並且不會以 null 終止。 因此scanf僅填充字符串的第一個值,在本例中為s[0] 由於字符串未被null terminator (\0)關閉, printf繼續打印整個數組,包括 memory 中已經存在的垃圾值。

您可以選擇在printf中使用%s格式化程序,以確保將 output 格式化為字符串。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    char s[40];
    scanf("%s", &s);
    printf("%s", s);

    return 0;
}

%c讀取單個字符。 您看到的“垃圾”字符是未定義行為的表現; 推測 UB 毫無意義,但您看到的是(未初始化的)數據恰好位於緩沖區的第二個字符和剩余字符中。 您可以通過使用char s[40] = ""初始化s來避免“垃圾”,但您可能想使用%s 由於要讀取數據的數組大小為 40,因此最多只能讀取 39 個字符。 必須檢查 scanf 返回的值。 如果scanf不讀取任何數據,則s保持未初始化狀態,嘗試讀取它是未定義的行為。 您不應該調用printf(s) ,因為s是未知數據並且可能包含格式。 使用fputsputs可能更明智。 例如:

int main(void)
{
    char s[40];
    if( scanf("%39s", &s) == 1 ){
        printf("%s\n", s);
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM