#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.
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);
The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With