为什么我这个输入字符串出现了问题啊?
#include <stdio.h>#include <string.h>
struct
{
char name;
int total;
}leader = { {"ben",0},{"tony",0},{"hans",0} };
void main()
{
int i;
char names;
do
{
printf("请输入一个名字,以便计票。\n");
scanf_s("%s", names);
for (i = 0; i < 3; i++)
{
if (strcmp(names, leader.name) == 0)
{
leader.total++;
}
else
{
printf("error\n");
}
}
} while (names != 32);
for (i = 0; i < 3; i++)
{
printf("%s", leader.name);
printf("%d\n", leader.total);
}
}
#include <stdio.h>
#include <string.h>
struct
{
char name;
int total;
}leader = { {"ben",0},{"tony",0},{"hans",0} };
void main()
{
int i;
char names;
do
{
printf("请输入一个名字,以便计票。\n");
scanf_s("%s", names,20);
for (i = 0; i < 3; i++)
{
if (strcmp(names, leader.name) == 0)
{
leader.total++;
}
else
{
printf("error\n");
}
}
} while (names != 32);
for (i = 0; i < 3; i++)
{
printf("%s", leader.name);
printf("%d\n", leader.total);
}
} 本帖最后由 baige 于 2020-8-29 17:01 编辑
https://blog.csdn.net/qq_43309823/article/details/95386759?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param 你的程序有几个问题,帮你修改了,并做了注释
另外,还有个地方帮你优化了,就是for循环内的if…else…,你写的这个if…else…会导致不管你输入的名字对不对,都至少会输出两次error
#include <stdio.h>
#include <string.h>
struct
{
char name;
int total;
}leader = { {"ben",0},{"tony",0},{"hans",0} };
void main()
{
int i,flag;
char names;
do
{
flag=1;//用于判断输入的名字是否在名字列表内
printf("请输入一个名字,以便计票。\n");
scanf_s("%s", names,20);//问题1:这个函数在读取输入字符串的时候要写上读取长度,不知道现在的版本是否需要写上长度参数,若不需要的话,这一条就当我没说。
for (i = 0; i < 3; i++)
{
if (strcmp(names, leader.name) == 0)
{
leader.total++;
flag=0;
break;
}
}
if (flag && names !=35)
printf("error\n");
getchar();//问题2:这里需要写上getchar()用来清除scanf遗留下来的回车字符
} while (names !=35);//问题3:这里不能以空格作为结束字符,因为空格在 scanf中很特殊,需要换成其他字符,我改成了'#'
for (i = 0; i < 3; i++)
{
printf("%s", leader.name);
printf("%d\n", leader.total);
}
}
页:
[1]