You can't (usefully) compare strings using != or ==, you need to use strcmp:
while (strcmp(check,input) != 0)
The reason for this is because != and == will only compare the base addresses of those strings. Not the contents of the strings themselves.
You can't (usefully) compare strings using != or ==, you need to use strcmp:
while (strcmp(check,input) != 0)
The reason for this is because != and == will only compare the base addresses of those strings. Not the contents of the strings themselves.
Ok a few things: gets is unsafe and should be replaced with fgets(input, sizeof(input), stdin) so that you don't get a buffer overflow.
Next, to compare strings, you must use strcmp, where a return value of 0 indicates that the two strings match. Using the equality operators (ie. !=) compares the address of the two strings, as opposed to the individual chars inside them.
And also note that, while in this example it won't cause a problem, fgets stores the newline character, '\n' in the buffers also; gets() does not. If you compared the user input from fgets() to a string literal such as "abc" it would never match (unless the buffer was too small so that the '\n' wouldn't fit in it).
Videos
How do we compare a substring of a string in C?
What is string comparison in C?
Can we compare strings in C without `strcmp()`?
Hello,
I am discussing with a person who believes that
std::string msg = "Hello";
if (msg == "Hello") { // UB?
...
}According to the person, this line "if (msg == "Hello") {" is UB.
Have you seen this "operator==" as UB?
I have checked the C++ specification (from c++11), and it's acceptable. I checked the std::string implementation (GNU GCC 5 and the latest) and operator== calls std::string::compare and then "traits". Passing cstring in operator== is fine too...
Toolchain is ARM for 32bit architecture and std is c++11/14.
His arguments are based on Stackoverflow posts which are more than 10y ago...
Thank you
I am an experienced dev, but have no C experience and i'm currently working through reverse engineering one of the flipper zero apps and this really caught me off guard
I'm very sorry if this has been explained before I'm just trying to wrap my head around it