简体   繁体   中英

Unexpected results when using std::stringstream

I am a beginner in C++, started last week. I am trying to make a simple program converting a number of inches to foot inch notation: Eg 62 turns into 5'2". However when I try to compile I have some error in line 8. I don't know what it is. Thanks in advance.

#include <iostream>
#include <sstream>
using namespace std;
string ConvertToFootInchMeasure (int totalInches){
    string feet = ""+totalInches/12;
    string inches = "" + totalInches%12;
    stringstream converted;
    conveted<<feet;
    converted<<"'";
    converted<<inches;
    converted<<"\"";
    return converted.str();
} 

That code can be easily fixed like this:

string ConvertToFootInchMeasure (int totalInches){
    stringstream converted;
    // Do inline calculations and use formatted text output for the results
    converted << (totalInches/12) << "'" << (totalInches%12) << "\"";
    return converted.str();
}

To explain further: You tried to concatenate the numeric results of the totalInches/12 and totalInches%12 operations to a std::string variable, but the right side of the statement doesn't do that.

Note:

std::string operator+(std::string, char c) doesn't do conversion of numerics to string and concatenation as you tried to use with:

string feet = ""+totalInches/12;

also it seems to be even worse in your case because the term

""+totalInches/12

does pointer arithmetics for a const char* pointer, and the string variable is initialized from eg a pointer address "" + (62/12) .

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