简体   繁体   中英

Neverending loop in C++, that compares two char's

I have this:

#include <iostream>
#include <conio.h>

int main ()
{
     char str1[] = "abc123";
     char str2[] = "abc123";
     do
     {
          std::cout << "String: ";
          std::cin >> str2;
     } while (str1 != str2);
     std::cout << "str1 is equal to str2, press any key to quit.\n";
     _getch();
     return 0;
}

The program should end when str1 is equal to str2, and str2 is a value set by the user. The problem is, even if I type the same value as str1, it keeps looping, it doesn't matter if I put the same contents as in str1 or not.

Use std::string instead of raw arrays and pointers, in order to avoid silly mistakes like opening up for buffer overflows, comparing pointers instead of strings, and so on.


#include <iostream>
#include <string>

int main ()
{
     std::string str1 = "abc123";
     std::string str2 = "abc123";
     do
     {
          std::cout << "String: ";
          std::cin >> str2;
     } while (str1 != str2);
     std::cout << "str1 is equal to str2.\n";
}

You are not properly comparing the two strings, you are comparing the addresses of the two char arrays.

You have to use the strcmp function.

while(strcmp(str1,str2)!=0)

Or use the std::string class, which allows you to use the overloaded operator == in order to compare strings.

str1 and str2 are char arrays, which really means they are pointers to char arrays. Their values are constant, and will never be equal. Replace the declarations with:

 string str1 = "abc123";
 string str2 = "abc123";

and you will get better results. (but will need header)

You are comparing the pointers.

Use strcmp rather.

Moreover, using cin is unsafe as left may be too small.

Modify as

} while(strcmp(str1, str2))

In the main function stack frame when you are allocating two array:

The two arrays get two different fixed addresses which never changes !

Even if the contents of the array are changed everytime !

char str1[] = "abc123";  // str1 gets an unique fixed address  say 1000
char str2[] = "abc123";  // str2 gets an unique fixed address  say 1007

Thus the statement while (str1 != str2); keeps on comparing the address 1000 and 1007 and

thus the loop condition becomes true all the time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM