首页 > 解决方案 > C程序返回带有答案的%

问题描述

我正在尝试使用函数来计算字符串的长度。我知道有一个预定义的功能,但我想自己做一个。但这里的问题是,每当我运行此代码时,它都会返回带有 % 的名称长度。像这样:

~ >>> /home/******/Coding/strlen                                         
Enter your name ==> Example
The length of your name is 7% 

我真的很困惑为什么会这样。请弄清楚我的代码有什么问题......我使用的是 GCC 版本 10.2.0

/*String Length Using Function*/
#include <stdio.h>
int find_length(char[]);
int main()
{
    char name[20];
    int l;
    printf("Enter your name ==> ");
    scanf("%s",name);
    l = find_length(name);
    printf("The length of your name is %d",l);
    return 0;   
}
int find_length(char tempname[])
{
    int len=0, i;
    for(i = 0; tempname [i]!='\0'; i++)
    {
        len++;
    }
    return len;
} 

标签: cgcc

解决方案


似乎您的外壳正在添加%以告诉您您的程序没有在输出末尾打印换行符。

在输出中添加换行符以防止这种情况发生。

    /* add \n to print a newline character */
    printf("The length of your name is %d\n",l);

推荐阅读