简体   繁体   中英

C++ Error in converting int to string

When I try to convert an int to string it produces weird results which I don't know where it comes from, here's a code snippet:

if (!ss.fail() && !ss.eof()) {
    ss.clear();

    string operand1 = "" + num1;
    string operand2 = "";
    getline(ss,operand2);   
    operand2 = trim(operand2);

    cout << num1 << endl << operand1 << endl;
    return expression_isvalid(operand1) && expression_isvalid(operand2) && operator_isvalid(c);

}

ss is a stringstream, num1 is an int, while c is a char.

basically the input is an expression like "1 + 1", num1 contains the first int it finds in that expression (using ss >> num1)

what I don't get is that this part

string operand1 = "" + num1; // assume input is "1 + 1" so num1 contains the value 1
...
cout << num1 << endl << operand1 << endl; 

outputs

1
exit

I have no idea where the "exit" comes from, the word changes depending on the input, "exit" becomes "it" when I input "3+1", and "ye," when I input "13+2".

I suggest you to use strtoul function of std. Here you can find a good documentation.

An example may be:

static unsigned long stringToInt(const string& str) {
  const char* cstr = str.c_str();
  char* endPtr = 0;
  return ::strtoul(cstr, &endPtr, 0);
}

You can use stringstream to convert various types in string . I generally use the following template to do that:

template <typename T>
static std::string strfrom(T x)
{
    std::ostringstream stream;

    stream << x;

    return stream.str();
}

Then to convert an int i into a string i_str , just do:

i_str = strfrom<int>(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM