How to Exit loop with constant literal ??

I am trying to make a while loop that exits when the user inputs the word "done" - however it loops endlessly. I am sure this is something simple that I am missing.. but its giving me a headache.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{

char checkItem[10];
bool exitLoop;

do
{
  cout << "Enter something (enter done to exit): ";
  cin.getline(checkItem, 10);

  if (checkItem == "done")
  {
    exitLoop = true;
  }
}
while(!exitLoop);

return 0;

}
This code
if (checkItem == "done")

doesn't compare two strings, but their adresses! You may use strcmp or string to compare two strings.

http://www.cplusplus.com/reference/clibrary/cstring/strcmp/

http://www.cplusplus.com/reference/string/string/
http://www.cplusplus.com/reference/string/string/compare/
Last edited on
TYVM! heres the code if anyone is interested...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string.h>
using namespace std;

int main()
{

char checkItem[10];
bool exitLoop;

exitLoop = false;

do
{
  cout << "Enter something (enter done to exit): ";
  cin.getline(checkItem, 10);

  if (strcmp(checkItem,"done") == 0)
  {
    exitLoop = true;
  }

  cout << "end of loop and bool is: ";
  if (exitLoop == true)
  {
	  cout << "TRUE\n";
  }
  else
  {
	  cout << "FALSE\n";
  }
}
while(!exitLoop);


cout << "Loop has exited !!! \n";

return 0;

}
doesn't compare two strings, but their adresses! You may use strcmp or string to compare two strings.


Are you sure because I almost 95% sure that it does compare two strings for example
1
2
3
4
5
6
7
8
9
10
11

string name;

cout << "Enter steven ";
getline( cin, name );

if ( name == "steven" ) 
{
     cout << "Your name is steven\n";
}


if they are not comparing why does this work?

(I was just informed that your are right but I still want to know why this works ? )
Last edited on
Yes, he is 120% sure.

1
2
3
4
5
6
7
8
9
10

char name[50];

cout << "Enter steven ";
getline( cin, name );

if ( name == "steven" ) 
{
     cout << "Your name is steven\n";
}

You can't make type changes and presume that the original case still applies.

checkItem (as does name above) degrades to a pointer to char -- for the purposes of this discussion you can just say it is a pointer to char.

Your name is a std::string, which has the equality operator == overloaded so that it can execute a function when the user says foo == "x" -- it is about the same as foo.compare( x ).

That's a world of difference.

Ah, I see your edit. (Sorry, I can be slow...) Yes, this is why. Hope this helps.
It does thanks
That's why you should just use strings.
I haven't found myself having to use char in a while I alway use string... Why would you use char over string?
Topic archived. No new replies allowed.