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

  • Thread starter Thread starter smize
  • Start date Start date
Click For Summary
The discussion focuses on a C++ program intended to convert a string to its hexadecimal representation. The primary issue arises from an incorrect comparison in the code, specifically the line where the program checks if a character in the string is equal to a space. The error message indicates that comparing a character (str[x]) with a string literal (" ") leads to unspecified behavior. The correct approach is to compare str[x] with a character literal (' '), which resolves the issue. The user expresses gratitude for the clarification and acknowledges their novice status in C++.
smize
Messages
78
Reaction score
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
Isn't str[x] a character? If so, you should compare it to a character ' ', not a string " ".
 
Thank you very much! Works perfectly! I'm such a novice -.-
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 40 ·
2
Replies
40
Views
3K
  • · Replies 118 ·
4
Replies
118
Views
9K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
12
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 89 ·
3
Replies
89
Views
6K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 5 ·
Replies
5
Views
3K