0

This is the second piece of code I have ever written don't seem to understand what I'm doing wrong. It seems to be going over my head as I have no prior knowledge of any programming language and have literally just begun. I have tried searching the issue to resolve it myself but have had no luck, other seem to look like mine (or not?). Anyway, any help would be appreciated.

Here's what I have:

#include <iostream>
using namespace std;

int main()
{
    char Name;

    cout << "Please input your name: ";
    cin >> Name;

    if ( Name == "Kyle A" ) 
    {
        cout << "Pass \n";
    }

    else if ( Name == "Mike C" ) 
    {
        cout << "Fail \n";
    }   

    else
    {
        cout << "Wrong name!! \n";
    }

    return 0;
}

Edited by mike_2000_17: Fixed formatting

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Narue
0

You need to make three changes for the code to work as intended:

  1. Add #include <string> to your headers
  2. Change char Name; to string Name;
  3. Change cin >> Name ; to getline(cin, Name);

There are two problems: first, char is only a single character type, not a string type. At most you'd be able to store the first letter of any input. Second, the >> operator stops reading when it encounters whitespace, so even if you use a string type for Name and type "Kyle A", the variable will only contain "Kyle" and fail your test. The getline function reads a full line of input.

Edited by Narue: n/a

0

Thank you very much, seems stupid but just getting used to it.

Cheers,
Kyle.

0

No worries, we were all there at one point. Just keep plugging away and it'll become second nature. :)

This article has been dead for over six months. Start a new discussion instead.
Be sure to adhere to our posting rules.