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

  • Context: C/C++ 
  • Thread starter Thread starter smize
  • Start date Start date
Click For Summary
SUMMARY

The forum discussion addresses a comparison error in a C++ string operator function. The issue arises from using a string literal " " instead of a character ' ' for comparison in the line if(str[x] == " "). The correct approach is to compare str[x] with a character type, which resolves the unspecified behavior error. The user successfully implements this correction, leading to the program functioning as intended.

PREREQUISITES
  • Understanding of C++ string manipulation
  • Familiarity with character data types in C++
  • Basic knowledge of C++ functions and loops
  • Experience with error handling in C++ programming
NEXT STEPS
  • Learn about C++ character and string comparisons
  • Explore C++ error handling techniques
  • Study C++ arrays and their initialization
  • Investigate best practices for input handling in C++
USEFUL FOR

Beginner C++ developers, programming students, and anyone looking to improve their understanding of string operations and error resolution 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 -.-
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 40 ·
2
Replies
40
Views
4K
  • · Replies 118 ·
4
Replies
118
Views
10K
  • · Replies 22 ·
Replies
22
Views
4K
  • · 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