问题:当输入为 * 和#时,用户需要重新输入名称。最大输入限制为25个字符,并以 enter 键结束输入。
#include <stdio.h>
#include <conio.h>
#define MAX 25
char welcomeMsg[]= "Please enter your name without '*' or # " ;
char errorMsg[]= "\nError, please re-type your name. ";
void main(void)
{
int j;
char input;
char name[MAX];
j=0;
puts(welcomeMsg);
do
{
input = getche();
if(input == '*' || input =='#' )
{
puts(errorMsg);
j = 0;
continue;
}
scanf("%s", name[j]);
j++;
} while ( j < MAX && input != '\r' );
name[j] = NULL;
puts("\nYour name is");
puts(name);
}
答案 0 :(得分:0)
scanf("%s", name[j]);
错了,写
name[j] = input;
代替。给定格式字符串,scanf将读取整个字符串, 但你的程序显然需要阅读字符。
您还需要
#include <stdio.h>
一开始。
哦,
name[j] < 25
应该是
j < MAX
更多错误修正:
char name[MAX+1]; /* one more for the terminating 0 */
name[j]=0; /* instead of NULL */
答案 1 :(得分:0)
我修改了你的代码。请参阅下面的snipet代码
#include <stdio.h>
#include <conio.h>
#define MAX 25
char welcomeMsg[]= "Please enter your name without '*' or # " ;
char errorMsg[]= "\nError, please re-type your name. ";
void main(void)
{
int j;
char input;
char name[MAX];
j=0;
puts(welcomeMsg);
do
{
input = getche();
if(input == '*' || input =='#' )
{
puts(errorMsg);
j = 0;
continue;
}
name[j] = input;
j++;
} while ( j < MAX && input != '\r' );
name[j] = 0;
puts("\nYour name is");
puts(name);
}
答案 2 :(得分:0)