Home > front end >  My last prompt answers itself. What do I do?
My last prompt answers itself. What do I do?

Time:10-07

I'm new to C, and I was trying to create a password system with 2 questions. 1. "What is your password?" I prompted the user to answer and recorded the argument. Any input was assigned to the variable. 2."Are you sure? Do you want this password? Enter Yes or No." It would decide whether to use the answer or discard it. Everything was working smoothly until this part. I couldn't type Yes or No. It automatically assumed that I had typed yes and saved it. Can somebody please give me some advice?

#include <stdio.h>

int
main ()
{
  char password;
  printf ("Hello User.");
  printf ("Please type in your password:");
  scanf ("%d", & password);
  
  char answer;
  printf ("\nAre you sure? Do you want this password? Enter Yes or No: \n");
  scanf ("%c", answer);
  printf ("\nAnswer is %c");
  if (answer == 'Yes')
  printf ("Confirmed.");
  
  else (answer == 'No');
  printf ("OK. Thank you.");
  password = 0;
  
  return 0;
}

CodePudding user response:

As noted in the comments, you likely didn't intend to store a password in a single character. Nor did you likely intend to scanf the password as an integer using, which is what you're saying with %d.

You may want to use getline instead to read an entire line, and store it in password if you declare it as char array.

Let's say you gave it room for 100 chars.

char password[100];

You might read your password in with:

getline(password, 100, stdin);

You can do the same for the second question, but should always use strcmp to compare strings in C. When the two strings are equal, the return value is 0. Be careful as this is opposite of the way that "true" is usually represented by integers in C.

if (strcmp(response, "yes") == 0) { 
    ...
}

Hopefully these tips will point you in the right direction.

CodePudding user response:

Research and study the functions and syntax.

#include <stdio.h>

int
main ()
{
  int password; // Must be an integer
  char line[100]; //C version of a String
  char answer;
  
  printf ("Hello User.");
  printf ("Please type in your password: ");
  fgets(line, sizeof(line), stdin); // read input
  sscanf(line, "%d", &password); // store password
  
  printf ("\nAre you sure? Do you want this password? Enter Y or N: \n");
  fgets(line, sizeof(line), stdin); //read input
  sscanf(line, "%c", &answer); // store answer
  
  printf ("\nAnswer is %c \n", answer); // print answer
  if (answer == 'Y') // 
   printf ("Confirmed.");
  else 
  {
    password = 0;
    printf ("OK. Thank you.");
  }
  return 0;
}

enter image description here

  •  Tags:  
  • c
  • Related