juergen d
juergen d

Reputation: 204766

Read number from file, increment and write back

I want to read a long number from file then increment it and write it back to file.
I am struggling with the convertion from string to long and back again.

I tried:

double id = atof("12345678901"); //using atof because numbers are too big for atio()
id++;
ostringstream strs;
strs << static_cast<long>((static_cast<double>(threadId)));
string output = strcpy_s(config->m_threadId, 20, strs.str().c_str());

But that converts the input to a negative or wrong number.

Upvotes: 2

Views: 2253

Answers (3)

Greyson
Greyson

Reputation: 3678

atoi is for normal integers. There's also atol and atoll (_atoi64 in windows):

//long long id = atoll( "12345678901" );
long long id = _atoi64("12345678901"); // for Visual Studio 2010
id++;
// write back to file here

As suggested by one commenter, use strtoll instead of the ato* functions:

char * data = "12345678901";
long long id = strtoull( data, NULL, 10 );
id++;

Since you're using C++ here, you should just pull it straight from the fstreams:

long long id;
{  
   std::ifstream in( "numberfile.txt" );
   in >> id;
}
id++;
{
   std::ofstream out( "numberfile.txt" );
   out << id;
}

Upvotes: 3

TemplateRex
TemplateRex

Reputation: 70526

Do you have access to Boost.Lexical_Cast? You could simply do the conversion like this:

double id = boost::lexical_cast<double>("some string");
++id
std::string id_string = boost::lexical_cast<std::string>(id);

and use whatever file transfer you currently have.

Upvotes: 1

inspector-g
inspector-g

Reputation: 4176

To go from a C string (char array), use this:

long id = atol("12345678901");

Now you can increment the number. Then, to go from a long to a C++ std::string, use this:

std::ostringstream oss;
oss << id;
std::string idAsStr = oss.str();

Now you can write the string back to the file.

Upvotes: 2

Related Questions