What is causing the comparison error in the string operator function in C++?

  • C/C++
  • Thread starter smize
  • Start date
In summary, the program is attempting to compare a character from the input string to a string literal, causing an error. The solution is to compare the character to a character literal instead.
  • #1
smize
78
1
#include <iostream>
#include <string>

using namespace std;

void str2hex(string str) {

int strlen = str.length(); // Assign the length of input/str to strlen
string hex[strlen]; // Initialize the Array hex with the length of the string for (int x = 0; x < strlen; x++){ // Create a for loop assigning the values of the string to hex as hexadecimal values. if (str[x] == " "){

hex[x] = 20;

}

}

}

int main()
{

string input; // Declaring the string which will be converted into HEX
getline(cin,input); // Gets the user's input for the string
str2hex(input); // Inserts the user's input into the str2hex function

return 0;
}

In this program the issue is occurring on the line with if(str[x] == " ") {

the error I'm getting is: comparison with string literal results in unspecified behaviour
I can't figure out what is wrong. I am new to C++ so please don't scold me. Thank - you.
 
Technology news on Phys.org
  • #2
Isn't str[x] a character? If so, you should compare it to a character ' ', not a string " ".
 
  • #3
Thank you very much! Works perfectly! I'm such a novice -.-
 

FAQ: What is causing the comparison error in the string operator function in C++?

1. What is the purpose of the string operator[]?

The string operator[] is used to access individual characters within a string. It allows you to retrieve, modify, or assign a specific character in the string.

2. How is the string operator[] different from other string methods?

The string operator[] is different from other string methods because it directly accesses and modifies individual characters, whereas other methods may manipulate the entire string or a specific section of it.

3. Can the string operator[] be used on other data types?

No, the string operator[] is specific to strings and cannot be used on other data types. Other data types may have their own specific operators for accessing individual elements.

4. Can the string operator[] be used to add characters to a string?

No, the string operator[] cannot be used to add characters to a string. It can only access and modify existing characters within the string. To add characters, you can use other string methods such as concat() or the addition operator (+).

5. Are there any limitations to using the string operator[]?

Yes, the string operator[] can only be used to access characters within the string based on their position. It cannot be used to search for specific characters or patterns within the string.

Similar threads

Replies
1
Views
1K
Replies
40
Views
3K
Replies
118
Views
7K
Replies
22
Views
2K
Replies
2
Views
1K
Replies
8
Views
2K
Replies
89
Views
4K
Replies
5
Views
4K
Back
Top