This question already has answers here:
Differences between C++ string == and compare()?
(9 answers)
Closed 7 years ago.
Lets say I have string a and string b
I know I have to use a.equals(b) to compare two strings but in C++, it looks like I can directly use if(a==b)..., and I also found that string has a compare() fuction, so which one should I use, == or compare()
use == when you want to test for equality. It call str1.operator ==(str2)
Use std::string::compare if you want to know whether string is less than, equal to or greater than other string. std::string::compare returns a negative number (if str1 is lexicographycally or in dictionary order less than str2), 0 or a positive number accordingly. (analogous to str1 - str2)
Related
This question already has answers here:
C++ Comparison of String Literals
(8 answers)
Closed 2 years ago.
I was trying to learn about "<" operator on c++ strings and tried some test cases. I realized the two codes which I thought should behave the same was giving different results. Below are the codes, what is the reason for this?
string s="test";
string k="tes";
cout<<(s<k)<<endl; //returns false so it prints 0
cout<<("test"<"tes")<<endl; // returns true so it prints 1
(s < k) compares the values of the strings as you would expect.
("test" < "tes") compares the pointers to the beginning of the string literals as the compiler decides to arrange them in memory. Therefore, this comparison may return 0 or 1 depending on the compiler and settings in use, and both results are correct. The comparison is effectively meaningless.
The "C way" to compare these string literals would be strcmp("test", "tes").
s and k are string objects for which a comparison operator has been defined and performs what you expect.
"test" and "tes" are pointers to char that hold the address of the locations where these characters are stored. Thus the comparison is on the addresses.
This question already has answers here:
Variable number of arguments in C++?
(17 answers)
Closed 4 years ago.
I am kind of stuck in pre C++ 11 land. How can I write a function that takes n strings and appends them to an ostreamstream?
void Foo(std::string first_part, ...){
std::ostringstream oss;
oss << first_part << ...; // cant do it
for(int i = 0; i < ....length(); i++){ // :|
}
}
If I lived in a perfect world I could do the above. Is there any other way pre C++ 11 to loop through the ... arguments?
Sorry, but it can't be done directly (at least not in portable code).
Attempting to pass a non-trivial type (including std::string) as a variadic argument gives undefined behavior.
If you want to do something similar, you could (for one example) pass the addresses of a number of strings rather than attempting to pass the strings themselves.
If you do that, you'll still have to contend with one other detail: you'll need to tell the receiving function the number of (addresses of) strings to expect.
From there, the receiving function would use va_start, va_arg and va_end to retrieve the data and do it's thing with them.
This question already has an answer here:
Comparing uint8_t data with string
(1 answer)
Closed 4 years ago.
I'm new to C and C++, and can't seem to work out how I need to compare these values:
Variable I'm being passed:
typedef struct {
uint8_t ssid[33];
String I want to match. I've tried both of these:
uint8_t AP_Match = "MatchString";
unsigned char* AP_Match = "MatchString";
How I've attempted to match:
if (strncmp(list[i].ssid, "MatchString")) {
if (list[i].ssid == AP_Match) {
if (list[i].ssid == "MatchString") {
// This one fails because String is undeclared, despite having
// an include line for string.h
if (String(reinterpret_cast<const char*>(conf.sta.ssid)) == 'MatchString') {
I've noodled around with this a few different ways, and done some searching. I know one or both of these may be the wrong type, but I'm not sure to get from where I am to working.
There is no such type as "String" defined by any C standard. A string is just an array of characters that are stored as unsigned values based on the chosen encoding. 'string.h' provides various functions for comparison, concatenation, etc. but it can only work if the values you are passing to it are coherent.
The operator "==" is also undefined for string comparisons, because it would require comparing each character at each index, for two arrays that may not be the same size and ultimately may use different encodings, despite the same underlying unsigned integer representation (raising the prospect of false positive comparisons). You can possibly define your own function to do it (note C doesn't allow overloading operators), but otherwise you're stuck with what the standard libraries provide.
Note that strncmp() takes a size parameter for the number of characters to compare (your code is missing this). https://www.tutorialspoint.com/c_standard_library/c_function_strncmp.htm
Otherwise you would be looking at the function strcmp(), which requires the input strings to be null-terminated (last character equal to '\0'). Ultimately it's up to you to consider what the possible combinations of inputs could be and how they are stored and to use a comparison function that is robust to all possibilities.
As a final side note
if (list[i].ssid == "MatchString") {
Since ssid is an array, you should know that when you do this comparison, you are not actually accessing the contents of ssid, but rather the address of the first element of ssid. When you pass list[i].ssid into strcmp (or strncmp), you are passing a pointer to the first element of the array in memory. The function then iterates over the entire array until it reaches the null character (in the case of strcmp) or until it has compared the specified number of elements (in the case of strncmp).
To match two strings use strcmp:
if (0==strcmp(str1, str2))
str1 and str2 are addresses to memory holding a null terminated string. Return value zero means the strings are equal.
In your case one of:
if (0==strcmp(list[i].ssid, AP_Match))
if (0==strcmp(list[i].ssid, "MatchString"))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
If I want to compare a string to another string ,is there any particular reason on why i should or shouldn't use
word1 ==word2;
versus
strcmp(word1,word2);
?
EDIT 1 : I made a mistake in my question ,forgot to use '==' instead of '='
word1 =word2;
You shouldn't use this because it is an assignment, not a comparison. The idiomatic way to compare two std::strings for equality is
bool eq = word1 == word2;
If you want to know if one of the strings is less-than the other, then use the std::string::compare method:
int cmp = word1.compare(word2); // beware: 0 means equality
If you declared your variables as std::string you must use:
word1 == word2
But if you declared them as char* you must use:
strcmp(word1, word2)
strcmp does more than simply check if both strings are equal. From the cplusplus.com reference I got that it
Returns an integral value indicating the relationship between the
strings: A zero value indicates that both strings are equal. A value
greater than zero indicates that the first character that does not
match has a greater value in str1 than in str2; And a value less than
zero indicates the opposite.
That's why it should be more efficient to use if (str1==str2)
The idiomatic way in C++ to use and process strings is to use the standard std::string one.
This class has comparison operators for your convenience:
#include <string>
int main () {
std::string foo = "foo", bar = "bar";
if (foo == bar) {
....
}
}
If you instead go the rough and errorful road of using char*, then the following is wrong:
const char *foo = "foo", *bar = "bar";
if (foo == bar) {
}
This just compares the addresses of the foo- and bar-strings as the variables are pointers really. As a beginner, both pointers and raw string processing are rather tough, so better start with the standard containers (if which std::string is one).
std::string is the more OOP way of doing strings in c++. A "string" as in a c string is actually an array of characters. Using == with that will not work as you might think, as it will compare the address of the first character (not the content of the string). For more info look up pointers. Here you use strcmp.
If you are using std::string (characterized by #include <string> and the declaration string myvar; instead of char* myvar) use ==.
This question already has answers here:
Using the equality operator == to compare two strings for equality in C [duplicate]
(9 answers)
Closed 8 years ago.
I am trying to parse the run-arguments within my console application with this code:
int _tmain(int argc, _TCHAR* argv[])
{
if(argv[1] == _T("arg1")) cout<<"Argument1 was passed";
_getch();
return 0;
}
My code doesn't work. I mean, it runs, but the console is empty.
I am compiling with Use Unicode Character Set option in Visual Studio 2012 (on Windows 7).
Where is my mistake?!
Use strcmp to compare char arrays
if(strcmp(argv[1], "arg1") == 0)
Use of == just compares pointers to two different strings.
See Darius Kucinskas' answer for comparing _TCHAR arrays
if (_tcscmp(argv[1], _T("arg1")) == 0) {
cout << "Argument1 was passed" << endl;
}
You have a few mistakes:
1) You cannot compare C-style strings (character arrays) using the == operator. argv[#] is a character array, as is _T("some value"). In order to compare them, you need to use strcmp (or one of it's cousins), or store it in a std::string.
2) You are attempting to access the 2nd element of the array, but only 1 element exists. you said you were passing nothing to the call, meaning argv[0] will contain data (the name of the executable you are running), but argv[1] will not. In general, attempting to access it will be attempting to access data outside the range of the array with undefined results. In this particular case, the standard (Section 3.6.2) states that it will always be 0 (aka NULL). So your conditional will always be false.
3) You should ALWAYS check the value of argc when command line parameters are expected.