【问题标题】:Why doesen't it clear screen in if method (C language only)为什么在 if 方法中不清除屏幕(仅限 C 语言)
【发布时间】:2014-08-20 11:11:05
【问题描述】:

我试图用 C 语言制作一个类似于 DOS 的 shell 解释器(显然是为了好玩)

当我输入 clear 时,如下面的代码所示,它应该可以清除屏幕。但事实并非如此。

    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    char command[128];
    int loop = 0;
    void main(){
        clrscr();
        printf("Starting shell\n");
        clrscr();
        while ( loop == 0){
            printf("command:");
            scanf("%s", &command);
            if(command=='clear'){
                printf("Clearing screen");
                clrscr();
            }  

/** Other Code **/

【问题讨论】:

  • scanf("%s", command); if(!strcmp(command, "clear")){ printf("Clearing screen"); clrscr(); }
  • 这里有很多基本的 C 错误。阅读有关这些函数的文档并做一些 C 教程。使用scanf("%s", command)if(!strcmp(command, "clear"))。 C 中的字符串使用双引号,而不是单引号。
  • 不要使用scanf("%s", command),而是使用fgets(command, sizeof commmand, stdin)

标签: c syntax command conio


【解决方案1】:
if(command=='clear')

这不是有效的字符串比较。使用strcmp比较C中的字符串。

应该是

if (!strcmp(command, "clear"))
{
   printf("Clearing screen");
   clrscr();
}

【讨论】:

  • 更不用说'clear' 不是一个有效的C 字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 2020-07-01
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
相关资源
最近更新 更多