无法检查空字符串

Not able to check an empty string

本文关键字:字符串 检查      更新时间:2023-10-16
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
    int t,l;
    char a[22];
    a[0]='0';
    for(t=1;t<=20;t++)
    {
        l=1;
        scanf("%s",a+1);
        if(strlen(a)>1)
            l=strlen(a);
        printf("%dn",l-1);
    }
     return 0;
}

当我输入长度为>= 1 的任何字符串时,我得到了字符串长度的正确答案,但是当只使用击键输入或空格时,它不会打印 0。由于字符串为空(仅包含零),因此它应该打印 0(l-1=0),因为如果条件为假。

使用 fgets .这个答案是给C的。

改变

scanf("%s",a+1);

fgets (a, sizeof (a), stdin);