Issue with stringoperator[]

  • Thread starter smize
  • Start date
  • #1
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 occuring 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.
 

Answers and Replies

  • #2
Borek
Mentor
28,805
3,297
Isn't str[x] a character? If so, you should compare it to a character ' ', not a string " ".
 
  • #3
78
1
Thank you very much! Works perfectly! I'm such a novice -.-
 

Related Threads on Issue with stringoperator[]

  • Last Post
Replies
15
Views
5K
Replies
2
Views
552
Replies
12
Views
689
  • Last Post
Replies
1
Views
1K
Replies
13
Views
1K
  • Last Post
Replies
7
Views
2K
  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
4
Views
878
  • Last Post
Replies
4
Views
2K
  • Last Post
2
Replies
25
Views
2K
Top