簡體   English   中英

如何在 C 中使用 scanf() 檢查輸入字符數組 (%s) 的長度

[英]How to check the length of input char array (%s) using scanf() in C

我需要使用函數scanf()檢查輸入的長度。 我正在使用字符數組 (%s) 來存儲輸入,但我無法檢查此輸入的長度。

下面是代碼:

#include <stdio.h>

char chr[] = "";
int n;

void main()
{
    printf("\n");
    printf("Enter a character: ");
    scanf("%s",chr);     
    printf("You entered %s.", chr);
    printf("\n");

    n = sizeof(chr);    
    printf("length n = %d \n", n);
    printf("\n");

}   

在我嘗試過的每種情況下,它都會為我返回輸出的“長度 n = 1”。

在這種情況下如何檢查輸入的長度? 謝謝你。

使用 scanf() 檢查輸入字符數組 (%s) 的長度

  • 不要使用原始的"%s" ,使用寬度限制:比緩沖區大小小 1。

  • 使用足夠大小的緩沖區。 char chr[] = ""; 只有 1 個char

  • 當輸入未讀取空字符時,使用strlen()確定字符串長度。

     char chr[100]; if (scanf("%99s", chr) == 1) { printf("Length: %zu\\n", strlen(chr)); }
  • 迂腐:如果代碼可能讀取空字符,則使用"%n"來存儲掃描的偏移量(這種情況很少或惡意遇到)。

     char chr[100]; int n1, n2; if (scanf(" %n%99s%n", &n1, chr, &n2) == 1) { printf("Length: %d\\n", n2 - n1); }

sizeof是一個編譯時一元運算符,可用於計算其操作數的大小。如果要計算字符串的長度,則必須使用strlen()像這樣

#include <stdio.h>
#include <string.h>
  
int main()
{
    char Str[1000];
  
    printf("Enter the String: ");
    if(scanf("%999s", Str) == 1) // limit the number of chars to  sizeof Str - 1
    {                            // and == 1 to check that scanning 1 item worked
        printf("Length of Str is %zu", strlen(Str));
    }
  
    return 0;
}

暫無
暫無

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

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