C使用char编程错误

时间:2016-09-21 16:08:32

标签: c

当我执行程序时,它会询问我的名字,如果我输了多个字母它有错误而且它关闭了,而在第二个字母中,我把它丢失并立即关闭

#include <stdio.h>

int main () {

   char firstname[20];
   char lastname[20];
   char response[20];

   printf ("Type your first name:\n");
   scanf ("'c'",&firstname);
   printf ("\n");  
   printf ("Type your last name:\n");
   scanf ("'c'",&lastname);
   printf ("\n");

   printf ("Hi %s %s do you want to stop giving me information?\nSay Y or  N");
   scanf ("%s",&response);

   if (response == 'Y' || response == 'y'); {
      system ("pause<NULL");
   }
   printf("Thank you for using my program. Good Bye!\n\n"); 

   system ("pause<NULL");
}

2 个答案:

答案 0 :(得分:1)

有很多问题:

你可能想要这个(未经测试的代码)

#include <stdio.h>

int main () {    
   char firstname[20];
   char lastname[20];
   char response[20];

   printf ("Type your first name:\n");
   scanf ("%s", firstname);
   printf ("\n");  
   printf ("Type your last name:\n");
   scanf ("%s", lastname);
   printf ("\n");

   printf ("Hi %s %s do you want to stop giving me information?\nSay Y or  N", firstname, lastname);
   scanf ("%s",response);

   if (response[0] == 'Y' || response[0] == 'y') {
      system ("pause<NULL");
   }
   printf("Thank you for using my program. Good Bye!\n\n"); 

   system ("pause<NULL");

   return 0;
}
  • 没有'c'格式说明符,它是%s
  • scanf ("%s", &firstname)错误,firstname已经是缓冲区的地址
  • response == 'y'错了,response是缓冲区的地址,你只需要缓冲区的第一个字符,即responde[0]
  • if (response[0] == 'Y' || response[0] == 'y'); {;
  • 之前有一个迷路{

答案 1 :(得分:0)

你的问题是你要求输入字符,你想要一个字符串。

tutorialspoint有一个simlpe和claean示例。 https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm