【问题标题】:Name cannot be display [closed]名称无法显示[关闭]
【发布时间】:2015-09-16 17:54:32
【问题描述】:

问题:当输入的是*和#时,用户需要重新输入名字。最大输入限制为 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。
  • main 声明错误!应该是int main(int argc, char**argv)。并且getche 没有定义。您应该测试scanf(扫描项目数)的结果
  • 当我在程序中输入名称时程序会崩溃。
  • 所以你有一个错误。编译所有警告和调试信息 (gcc -Wall -Wextra -g) 并使用调试器 (gdb);然后思考找出错误

标签: c char user-input scanf


【解决方案1】:

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

#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】:
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 */

【讨论】:

  • 为了显示 25 个字符及以下的名称,我们需要使用键盘上的 4 个箭头键以及 { } 、 .等
  • 对箭头键等的支持绝对超出了这里简单回答的范围,这需要更多的代码。
【解决方案3】:

由于各种原因,您的程序出错了,例如

  • scanf("%s", name[j]);、%s 需要一个指向 char 数组的指针。
  • name[j] = NULL;,NULL是指针类型

等等

相反,我建议您使用更清洁的算法。看看你喜不喜欢。

  1. 使用fgets() 读取用户输入。
  2. 使用strpbrk() 搜索* 或# 或任何其他(根据需要)是否存在。
  3. 如果strpbrk() 返回NULL,这意味着您可以进一步使用输入。 限制 chars 不存在。
  4. 否则,请重新输入。

也就是说,void main(void) 不是main() 的推荐签名,您应该改用int main(void)。

【讨论】:

    猜你喜欢
    • 2014-09-07
    • 2017-12-30
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2011-08-19
    • 2020-06-17
    • 2015-10-24
    • 2019-01-25
    相关资源
    最近更新 更多