到达“ cin << ans1”时,我的程序崩溃

时间:2019-10-21 09:48:58

标签: c++

此程序到达cin >> ans1;时实际上会崩溃。 我在atom中编写了此代码,但在code::blocks中尝试了相同的程序,它运行良好。我的atom编译器是否有问题...

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

string name[30];
string gender;
int age;

void Job()
{
  printf("To apply for Job, Plz Enter your name: ");
  getline(cin, name[20]);
  printf("Enter Your Gender: ");
  cin >> gender;
  printf("Enter your age: ");
  cin >> age;
  printf("\n");

  while (age > 100)
  {
    printf("Enter a real age Dumbass: ");
    cin >> age;
  }

  return;
}

int main(int argc, char const *argv[])
{
  Job();
  char ans1;

  printf("\n");
  printf("Entered Information is...\n");
  cout << "Name: " << name[20] << "       " << "Sex: " << gender << endl;
  cout << "Age: " << age;
  printf("Is this Correct?(y/n): ");
  cin >> ans1;

  if (ans1 == 'y')
  {
    if (age < 60 && age > 14 )
    {
      printf("It seems that you are eligible to vote...\n");
      printf("Go to our Website to Sign up...\n");   /* code */
    }
    else
    {
      printf("Sorry... But you are not Eligable to be hired...\n");
    }
  }
  else
  {
    while(ans1 != 'y')
    {
       printf("Write again...\n");
       Job();
    }
  }
  return 0;
}

1 个答案:

答案 0 :(得分:0)

首先,将ans1 != y放入while循环是没有意义的,因为ans1不会改变,并且尝试使用此方法不会有新的事情发生

#include <cstdio>
    #include <cstdlib>
    #include <iostream>
    #include <string>
using namespace std;

string name[30];
string gender;
int age;

void Job()
{
  printf("To apply for Job, Plz Enter your name: ");
  getline(cin, name[20]);
  printf("Enter Your Gender: ");
  cin >> gender;
  printf("Enter your age: ");
  cin >> age;
  printf("\n");

  while (age > 100)
  {
    printf("Enter a real age Dumbass: ");
    cin >> age;
  }

  return;
}

void h()
{
  Job();
  char ans1;

  printf("\n");
  printf("Entered Information is...\n");
  cout << "Name: " << name[20] << "       " << "Sex: " << gender << endl;
  cout << "Age: " << age;
  printf("Is this Correct?(y/n): ");
  cin >> ans1;

  if (ans1 == 'y')
  {
    if (age < 60 && age > 14 )
    {
      printf("It seems that you are eligible to vote...\n");
      printf("Go to our Website to Sign up...\n");   /* code */
    }
    else
    {
      printf("Sorry... But you are not Eligable to be hired...\n");
    }
  }
  else
  {
    if(ans1 != 'y')
    {
       printf("Write again...\n");
       h();
    }
  }

}

int main()
{
    h();
}