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

  • Thread starter Thread starter smize
  • Start date Start date
AI Thread 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 -.-
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...

Similar threads

Replies
1
Views
1K
Replies
40
Views
3K
Replies
22
Views
3K
Replies
2
Views
2K
Replies
8
Views
2K
Replies
89
Views
6K
Replies
5
Views
3K
Back
Top