程序帮助!用户点击后输入程序结束

时间:2015-01-30 07:44:20

标签: c char ascii

好的我正在创建一个程序,从用户读取两个字符,然后在这两个字符之间打印ASCII字母。 问题是当程序运行时它会提示用户输入第一个字符,一旦用户点击进入程序结束。 我错过了什么?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){


      char firstchar;
      char secondchar;
      int variable;
      int highest;
      int lowest;
      char ASCIvariable;

      printf("Please enter a character. ");
      scanf("%d", &firstchar);

      printf("Please enter another character. ");
      scanf("%d", &secondchar);

      if(firstchar < secondchar) 
      {
         secondchar = highest;
         firstchar = lowest;
      }else{
         firstchar = highest;
         secondchar = lowest;
      }

      variable = lowest;

      for ( variable != highest; variable < highest; variable++ )
      {
          variable = ASCIvariable;
          printf(ASCIvariable);
      }

      return 0;
}

我显然也不了解如何在此网站上发布代码。我需要在每行代码之前手动输入四个空格?


这里更新的是当前代码也控制k不允许粘贴....

#include <stdio.h>
#include <stdlib.h>



 int main(int argc, char *argv[]) {


    char firstchar;
  char secondchar;
   int variable;
  int highest;
  int lowest;
  char ASCIvariable;

  printf("Please enter a character. ");
  scanf(" %c", &firstchar);

  printf("Please enter another character. ");
  scanf(" %c", &secondchar);

  if(firstchar < secondchar) 
  {
 highest = secondchar;
 lowest = firstchar;
}
  else
  {
  highest = firstchar;
  lowest = secondchar;
}

  variable = lowest;


 for (variable != highest; variable <= highest; variable++ )
  {
        ASCIvariable = variable;
      printf("%c ", ASCIvariable);

  }


    return 0;
}

它成功地允许用户输入两个字符,然后在两者之间打印字母。我认为这是正确的吗?

3 个答案:

答案 0 :(得分:1)

将您的代码更改为:

printf("Please enter another character. ");
scanf(" %c", &secondchar);  /* Note the extra space and %d is changed to %c*/

还要将for循环更改为:

for ( ; variable <= highest; variable++ ) /* Should be <= */ {
   ASCIvariable = variable; /* Reverse */
   printf("%c", ASCIvariable); /* %c */
}

您的作业也不正确:

if(firstchar < secondchar) 
{
 highest = secondchar;
 lowest = firstchar;
}
else
{
  highest = firstchar;
  lowest = secondchar;
}

a = b;表示将b的内容复制到a

答案 1 :(得分:1)

使用错误的格式说明符可能会导致UB。你需要扫描一个角色

scanf("%c", &firstchar);

然后使用

刷新换行符
scanf(" %c",&secondchar);

%c之前的空格使用换行符。

答案 2 :(得分:1)

1)您必须为字符

输入格式说明符%c

2)输入第一个字符后必须使用newline

3)你似乎对作业陈述感到困惑

a=bb的值赋予a,而不是相反。

printf("Please enter a character. ");
scanf(" %c", &firstchar);
//The space before %c will consume the newline

printf("Please enter another character. ");
scanf(" %c", &secondchar);

if(firstchar < secondchar) 
{
    highest=secondchar ;
    lowest=firstchar ;
}
else
{
    highest=firstchar;
    lowest= secondchar ;
}

//Changed the for loop to get characters between two inputs
variable = lowest+1;
for ( ; variable < highest; variable++ )
{
     ASCIvariable= variable ;
     printf("%c ", ASCIvariable);

}