int thetime = time(NULL);
string in;
stringstream out;
out << thetime;
in = out.str();

that's my code for casting an integer into a string, but im having a little trouble reversing it to change a string into an int. :/ can anybody help me out? you have to include the sstream library. thanks!

Dani AI

Generated

: is right — stringstreams will do the job — but there are clearer, more modern options and a couple of gotchas to watch out for.

If you use C++11 or later, prefer std::to_string for int->string and std::stoi for string->int. std::stoi throws std::invalid_argument when the input is not a number and std::out_of_range on overflow, so wrap it when you need robust error handling:

// C++11+
std::string s = std::to_string(thetime);

try {
    int v = std::stoi(s);
    // use v
} catch (const std::invalid_argument&) {
    // not a number
} catch (const std::out_of_range&) {
    // value too large
}

For maximum speed and no exceptions (C++17+), use std::from_chars; it returns a status you can check and does not allocate:

// C++17+
#include <charconv>

int v;
auto res = std::from_chars(s.data(), s.data() + s.size(), v);
if (res.ec == std::errc()) {
    // parsed OK
} else {
    // handle invalid input or out_of_range
}

If you must use C APIs, prefer std::strtol with end-pointer checks over atoi (atoi gives no error info). Also note: time(NULL) returns time_t — storing that directly in an int can truncate on some platforms; keep it in time_t or cast to a wider integer before converting to string.

Recommended Answers

All 2 Replies

its nearly the same thing

string in = "123";
stringstream out;
out << in;
int thetime;
out >> thetime;

thanks :) my brain stopped working for a moment there

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.