Thread: Else if Statement not working correctly

  1. #1
    Registered User
    Join Date
    Jan 2018
    Posts
    1

    Else if Statement not working correctly

    Hi,

    I am a beginner C++ programmer and I am trying to code in a way that makes it so that if the name provided is an empty string, then the response would be "You must enter a valid name". But my if statement is not working properly because even if the code is not an empty string, it is still saying "You must enter a valid name". Please help me.

    Here is a snippet of the code.

    insert
    Code:
    int main()
    {
    	string donorName;
    	string donorGender;
    	int donorWeight;
    	int donorHeight;
    	int donorAge;
    
    
    	cout << "What is the donor's name?" << endl;
    	cin.ignore(INT_MAX, '\n');
    	getline(cin, donorName);
    
    
    	cout << "What is the donor's gender?" << endl;
    	cin >> donorGender;
    
    
    	cout << "What is the donor's age?" << endl;
    	cin >> donorAge;
    
    
    	cout << "What is the donor's weight(in pounds)?" << endl;
    	cin >> donorWeight;
    
    
    	cout << "What is the donor's height?" << endl;
    	cin >> donorHeight;
    
    
    
    
    	if (donorName == "")
    	{
    		cout << " --- You must enter a valid name." << endl;
    		return (-1);
    	}
    
    
    	 else if (donorGender != "Male" && donorGender != "Female" && donorGender != "Trans Male" && donorGender != "Trans Female" && donorGender != "Queer" && donorGender != "Different")
    	{
    		cout << "--- You must enter a valid gender." << endl;
    		
    	}

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,627
    Start with removing the cin.ignore line.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 08-23-2015, 03:35 PM
  2. Am I doing this homework problem correctly? (Switch Statement)
    By Cameron Taylor in forum C Programming
    Replies: 5
    Last Post: 06-17-2013, 08:04 PM
  3. loop not working correctly
    By ilndboy11 in forum C Programming
    Replies: 2
    Last Post: 11-01-2012, 09:25 PM
  4. Pointers are not working correctly
    By adrian_fpd in forum C Programming
    Replies: 8
    Last Post: 11-17-2008, 07:55 PM
  5. File I/O not working correctly
    By gL_nEwB in forum C++ Programming
    Replies: 4
    Last Post: 05-27-2006, 10:29 PM

Tags for this Thread