c - 名称无法显示

标签 c char user-input scanf

问题:当输入*#时,用户需要重新输入名称。最大输入限制为 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);
}

最佳答案

我修改了你的代码。请参阅下面的片段代码

#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);
}

enter image description here

关于c - 名称无法显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129738/

相关文章:

c - 线程服务器,在客户端之间发送消息

c - 何时使用多个流在 CUDA 中获益?

Java System.getProperty ("line.separator") 在 apache 服务器中不工作

java - 代码似乎陷入了潜在的循环

python - 等待用户输入或按定义的时间间隔运行的程序?

c - 如何写入空文件中的特定偏移量

c++ - 如何在 GDB 中调试程序时获取程序的环境

c - 在 Char 数组中查找字符串值

C++ 创建一个 char* 迭代器

node.js - 简单的是/否脚本会产生奇怪的行为