Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot overwrite stringstream variable with a new value

string whatTime(int seconds) {

 string h,m,s,ans;
 stringstream ss;

 ss << (seconds/3600); 
 seconds -= (3600*(seconds/3600));
 ss >> h;
 ss.str("");

 ss << (seconds/60);
 seconds -= (60*(seconds/60));
 ss >> m;
 ss.str("");

 ss << seconds;
 ss >> s;


 return (h + ":" + m + ":" + s );

}

Output for above program is coming in this format "some_value::" I have also tried ss.str(std::string()) and ss.str().clear() but even that doesn't work. Could somebody please suggest any ways how to tackle this problem?

like image 578
Rishabh Avatar asked Dec 15 '12 11:12

Rishabh


2 Answers

You've correctly emptied the string buffer with ss.str(""), but you also need to clear the stream's error state with ss.clear(), otherwise no further reads will be attemped after the first extraction, which led to an EOF condition.

So:

string whatTime(int seconds) {

 string h,m,s,ans;
 stringstream ss;

 ss << (seconds/3600); 
 seconds -= (3600*(seconds/3600));
 ss >> h;
 ss.str("");
 ss.clear();

 ss << (seconds/60);
 seconds -= (60*(seconds/60));
 ss >> m;
 ss.str("");
 ss.clear();

 ss << seconds;
 ss >> s;


 return (h + ":" + m + ":" + s );

}

However, if this is your full code and you do not need the individual variables for any reason, I'd do this:

std::string whatTime(const int seconds_n)
{
    std::stringstream ss;

    const int hours   = seconds_n / 3600;
    const int minutes = (seconds_n / 60) % 60;
    const int seconds = seconds_n % 60;

    ss << std::setfill('0');
    ss << std::setw(2) << hours << ':'
       << std::setw(2) << minutes << ':'
       << std::setw(2) << seconds;

    return ss.str();
}

It's much simpler. See it working here.

In C++11 you can avoid the stream altogether using std::to_string, but that doesn't allow you to zero-pad.

like image 117
Lightness Races in Orbit Avatar answered Oct 24 '22 04:10

Lightness Races in Orbit


You need to call the clear method of the stringstream rather than on the string returned by the stringstream using ss.clear().

string whatTime(int seconds) {

 string h,m,s,ans;
 stringstream ss;

 ss << (seconds/3600); 
 seconds -= (3600*(seconds/3600));
 ss >> h;
 ss.str("");
 ss.clear();

 ss << (seconds/60);
 seconds -= (60*(seconds/60));
 ss >> m;
 ss.str("");
 ss.clear();

 ss << seconds;
 ss >> s;


 return (h + ":" + m + ":" + s );

}
like image 33
ctor Avatar answered Oct 24 '22 02:10

ctor