arrays - 打印字符串的前 N 个字符 (C)
问题描述
我的目标是使用简单的 for 循环打印出字符串的前 N 个字符(len变量)。但是,代码似乎不起作用。例如,输入printFrstChars("Example",3)
的代码应该打印出来Exa
,但它不会打印出任何东西。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void printFrstChars (char inp[], int len)
{
for(int i = 0; inp[i] != '\0' && i <= len; i++){
printf("%s", inp[i]);
}
}
int main ()
{
int len = 0;
char inp[100];
printf("Input string and length:\n");
scanf("%99s %d", &inp, &len);
printFrstChars(inp, len);
return 0;
}
我多次检查代码,我(显然)没有找到导致这种情况的错误。我猜这要么是一个足以隐藏在我初学者眼中的错误,要么是整个方法都是错误的。
解决方案
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void printFrstChars (char inp[], int len)
{
for(int i = 0; inp[i] != '\0' && i < len; i++){
printf("%c", inp[i]);
}
printf("\n");
}
int main ()
{
int len = 0;
char inp[100];
printf("Input string:\n");
scanf("%99s", inp);
printf("Input length (99 or less):\n");
scanf("%d", &len);
printFrstChars(inp, len);
return 0;
}
分离输入,扫描到inp
而不是,用格式&inp
打印每个字符,然后迭代 while (之后打印新行)。我的 2 美分。%c
i < len
编辑
感谢@AndrewHenle 指出溢出。格式说明%99s
符最多只能读取 99 个字符(并且提示也说明了这一点)。
推荐阅读
- keycloak - 用于身份联合的 Keycloak 反向通道注销
- python - 在同一个 conda 环境中安装 Python3.9 和 PyPy3.7
- java - 如何以相反的方式对对象列表进行排序?
- selenium - 我能否为单个 UI 元素提供多个辅助功能 ID?
- python - Python 磁场图
- angular - 显示带有嵌套动态对象 Angular 的 mat-table
- bash - 转换用空格分隔的列表 - 将每个项目放在一个新行上并在其前面加上一个连字符
- ios - 无法发出预编译头 Xcode 12 MacBook M1
- python - 如何用另一个列表或字典匹配替换熊猫数据框列名
- python - FileNotFoundError:[Errno 2]:没有这样的文件或目录:'C:/Users/My_computer/Desktop/Compare/MHAN-master/AID_train/AID_train_LR/x4\\9.png'