2

I am new to programming and this is my second assignment. It is supposed to accept input from user until they enter the | to exit the program. What have I done wrong?

int main()

    int i = 0;
    char a = 0;
        while ( a != "|" ){  //has also told me this is an
                             // invalid operator
    int numeric;
    cout << "Give character: ";
    cin >> a ;
    cout << "Its ascii value is: " << (int) a << endl;
    ++i;

    }
}

Here is the error:

2   IntelliSense: operand types are incompatible ("char" and "const char *")    
3
  • 2
    Use 's instead of "s Commented Feb 12, 2015 at 1:04
  • 3
    Enclosing stuff inside "s results in a string literal, which is of type const char *. This is a pointer to an array of characters. You can't compare a single char to an array of characters. Use |. Commented Feb 12, 2015 at 1:05
  • @BWG: "string literal, which is of type const char *" - a string literal is actually an array of const char, not a const char*; the confusion's not uncommon given the standard conversion to const char* kicks in quite readily. The difference is significant: e.g. for sizeof and when passing it to template <size_t N> void f(char (&s)[N]);. Commented Feb 12, 2015 at 1:36

2 Answers 2

3

Don't use "|". Put '|' instead. You want to compare a char to a char, NOT compare a char to a char*.

Sign up to request clarification or add additional context in comments.

1 Comment

"NOT compare a char to a char*" - my comment to BWG under the question is relevant here too.
1

You shall use while ( a != '|' ) instead

'|' is a character and "|" is a string which has only 1 character

2 Comments

""|" is a string which has only 1 character" - that's debatable... "|" is a string literal composed of '|' and NUL / '\0', which is '|' with a terminating sentinel in ASCIIZ encoding....
@TonyD You are right. LOL. Let's say "one valid character"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.