【发布时间】:2021-12-27 18:57:42
【问题描述】:
我写了一个简单的程序,程序按顺序输入并打印出字符并计数
char name[100];
int counter=0
printf("Enter name and surname:");
scanf("%s",&name);
for(int i=0; i<(strlen(name)); i++){
printf("%c \n",name[i]);
counter++;
printf("%d",counter)
由于某种原因,当我输入 John Snow 时,它只打印出来
J
o
h
n
4
想要的输出
J
o
h
n
S
n
o
w
10
有什么帮助吗?在合理的技能水平内:D 如果可能没有 malloc() free() 和内存的东西,它应该很容易:D
【问题讨论】:
-
%s只读取一个单词。里面不能有空格。 -
顺便说一句,在
name之前删除&。当用作函数参数时,数组会自动衰减为指针。 -
oh dam.... 我该如何修复它以使用空格读取?
-
使用
fgets()读取整行输入。 -
您可以改为阅读整行,例如使用
fgets。但是您可能还想阅读Removing trailing newline character from fgets() input。
标签: c scanf c-strings fgets strlen