c - 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;
}
解决方案
似乎您的外壳正在添加%
以告诉您您的程序没有在输出末尾打印换行符。
在输出中添加换行符以防止这种情况发生。
/* add \n to print a newline character */
printf("The length of your name is %d\n",l);
推荐阅读
- python - 如何让 Python 尝试从本地文件夹加载模块?
- javascript - 如何在 Visual Studio 中定义 HTML 文件扩展名?
- android - ConcatAdapter 内部的 Paging3 Library 的 PagingDataAdapter 加载所有页面而不滚动
- python - 如何组合多个条目的两个字典列表
- php - 如何修复在 yii2 中获取未知属性
- python - Python qtcreator 被自动踢出应用程序
- flutter - Flutter/Dart 扩展和智能感知不适用于 VSCode
- azure - 部署 Web 服务时出现 Azure 应用服务问题(PHP 和 MySQL)
- python-3.x - 在 ROS 中使用 pcl 和 python
- wpf - WPF MVVM 存储库模式实现