Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Issue with stringoperator[]

  1. Jun 26, 2012 #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.
     
  2. jcsd
  3. Jun 26, 2012 #2

    Borek

    User Avatar

    Staff: Mentor

    Isn't str[x] a character? If so, you should compare it to a character ' ', not a string " ".
     
  4. Jun 26, 2012 #3
    Thank you very much! Works perfectly! I'm such a novice -.-
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Issue with stringoperator[]
  1. Ifstream issues (Replies: 8)

  2. Strmm Issue (Replies: 1)

  3. Weird C++ Array Issue (Replies: 15)

  4. Issues with C++ errors? (Replies: 13)

Loading...