简体   繁体   English

如何在 C 中使用 scanf() 检查输入字符数组 (%s) 的长度

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

I need to check the length of an input using the function scanf() .我需要使用函数scanf()检查输入的长度。 I'm using an array of char (%s) to store the input, but I wasn't able to check the length of this input.我正在使用字符数组 (%s) 来存储输入,但我无法检查此输入的长度。

this below is the code:下面是代码:

#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");

}   

it's giving me back that "length n = 1" for the output in each case I've tried.在我尝试过的每种情况下,它都会为我返回输出的“长度 n = 1”。

How can I check the length of the input in this case?在这种情况下如何检查输入的长度? Thank You.谢谢你。

to check the length of input char array (%s) using scanf()使用 scanf() 检查输入字符数组 (%s) 的长度

  • Do not use the raw "%s" , use a width limit: 1 less than buffer size.不要使用原始的"%s" ,使用宽度限制:比缓冲区大小小 1。

  • Use an adequate sized buffer.使用足够大小的缓冲区。 char chr[] = ""; is only 1 char .只有 1 个char

  • Use strlen() to determine string length when the input does not read null characters .当输入未读取空字符时,使用strlen()确定字符串长度。

     char chr[100]; if (scanf("%99s", chr) == 1) { printf("Length: %zu\\n", strlen(chr)); }
  • Pedantic: Use "%n" to store the offset of the scan if code might read null characters (this is rarely or nefariously encountered).迂腐:如果代码可能读取空字符,则使用"%n"来存储扫描的偏移量(这种情况很少或恶意遇到)。

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

sizeof is a compile time unary operator which can be used to compute the size of its operand.if you want to calculate the length of the string the you have to use strlen() .like this 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