Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare string with const char*?

Tags:

c++

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
        string cmd;
        while(strcmp(cmd.c_str(),"exit")==0 && strcmp(cmd.c_str(),"\exit")==0)
        {
                cin>>cmd;
                cout<<cmd;
        }
        return 0;
}

I am stuck.

like image 522
Arzet Ro Avatar asked May 28 '10 18:05

Arzet Ro


People also ask

Can you compare a string to a char?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);

Can you compare string with char in C?

The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

Can you compare two strings using the == operator C++?

Using C++, we can check if two strings are equal. To check if two strings are equal, you can use Equal To == comparison operator, or compare() function of string class.


1 Answers

A std::string instance can be compared directly with a string literal using != or == operators. This makes your comparison clearer.

Note that \e isn't a valid character escape, you need to double the \ if you meant a literal \\.

while( cmd == "exit" && cmd == "\\exit" )

Obviously cmd can't be equal to two different strings at the same time, presumably you meant !=.

Also, consider whether std::getline( std::cin, cmd ) is more appropriate than std::cin >> cmd;. In either case you should check for success of the read operation otherwise you may end in an infinite loop if the stream is closed or enters a failed state.

Personally I'd go with something like this, assuming that you want to echo the exit command as your code does.

#include <string>
#include <iostream>
#include <ostream>

int main()
{
    std::string cmd;
    while (std::getline(std::cin, cmd))
    {
        std::cout << cmd << std::endl;
        if (cmd == "exit" || cmd == "\\exit")
            break;
    }
    return 0;
}
like image 115
CB Bailey Avatar answered Oct 17 '22 23:10

CB Bailey