Getting a unix timestamp as a string in C++ - c++

I'm using the function time() in order to get a timestamp in C++, but, after doing so, I need to convert it to a string. I can't use ctime, as I need the timestamp itself (in its 10 character format). Trouble is, I have no idea what form a time_t variable takes, so I don't know what I'm converting it from. cout handles it, so it must be a string of some description, but I have no idea what.
If anyone could help me with this it'd be much appreciated, I'm completely stumped.
Alternately, can you provide the output of ctime to a MySQL datetime field and have it interpreted correctly? I'd still appreciate an answer to the first part of my question for understanding's sake, but this would solve my problem.

time_t is some kind of integer. If cout handles it in the way you want, you can use a std::stringstream to convert it to a string:
std::string timestr(time_t t) {
std::stringstream strm;
strm << t;
return strm.str();
}

I had the same problem. I solved it as follows:
char arcString [32];
std::string strTmp;
// add start-date/start-time
if (strftime (&(arcString [0]), 20, "%Y-%m-%d_%H-%M-%S", (const tm*) (gmtime ((const time_t*) &(sMeasDocName.sStartTime)))) != 0)
{
strTmp = (char*) &(arcString [0]);
}
else
{
strTmp = "1970-01-01_00:00:00";
}

Try sprintf(string_variable, "%d", time) or std::string(itoa(time))?

http://www.codeguru.com/forum/showthread.php?t=231056
In the end time_t is just an integer.

Related

How to add current time to a string concisely in C++?

I'd like to add a timestamp to the filename in this part of my code:
takeScreenshot( "screenshot.png" );
But all ways of doing this that I've found seem unnecessarily long and complicated. E.g. creating a new string, loading a time struct, converting an element of the time struct to a char array and appending it to the string.
Is there a short way to accomplish this? Most other languages would have some simple solution like:
takeScreenshot( sprintf( "screenshot-%d.png", time() ) );
Is there one in C++? The time format doesn't matter.
Concatenating a string is long and complicated, under the hood.
A nice way is to use std::stringstream which overloads << for concatenation:
std::stringstream ss;
ss << "screenshot-" << time() << ".png";
std::string s = ss.str();
and format time() to personal taste.
You can use stringstream or just use + operator between strings:
takeScreenshot("screenshot-" + time() + ".png");

testing for double in visual c++

I am designing a gui in visual c++ and there is a textbox where user inputs values so a calculation can be performed. How do I validate the input to ensure it can be cast to a double value?
In any C++ environment where you have a std::string field and wish to check if it contains a double, you can simply do something like:
#include <sstream>
std::istringstream iss(string_value);
double double_value;
char trailing_junk;
if (iss >> double_value && !(iss >> trailing_junk))
{
// can use the double...
}
As presented, this will reject things like "1.234q" or "-13 what?" but accept surrounding whitespace e.g. " 3.9E2 ". If you want to reject whitespace, try #include <iomanip> then if (iss >> std::noskipws >> double_value && iss.peek() == EOF) ....
You could also do this using old-style C APIs:
double double_value;
if (sscanf(string_value.c_str(), "%lf%*c", &double_value) == 1)
You cannot "cast" a string to a double, you can only convert it. strtod function will return a pointer to the character within the string where the conversion stopped, so you can decide what to do further. So you can use this function for conversion AND checking.
I'd recommend Boost's lexical_cast, which will throw an exception if the conversion fails.
Since this seems to be a C++ CLI related question and your string from the textbox might be a .NET string, you might want to check the static Double::Parse method. For more portable solutions see the other answers...
As stated already, strtod(3) is the answer.
bool is_double(const char* str) {
char *end = 0;
strtod(str, &end);
// Is the end point of the double the end of string?
return end == str + strlen(str);
}
To address #Ian Goldby's concern, if white space at the end of the sting is a concern, then:
bool is_double(const char* str) {
char *end = 0;
strtod(str, &end);
// Is the end point of the double plus white space the end of string?
return end + strspn(end, " \t\n\r") == str + strlen(str);
}
Simply convert it to a double value. If it succeeds, the input is valid.
Really, you shouldn't be writing your own rules for deciding what is valid. You'll never get exactly the same rules as the library function that will do the actual conversion.
My favourite recipe is to use sscanf(), and check the return value to ensure exactly one field was converted. For extra credit, use a %n parameter to check that no non-whitespace characters were left over.

Float64 to string

In C++, how can I convert a data of type float64 to a string without losing any of the data in float64? I need it to not only be converted to a string, but add a string to either side of the number and then sent to be written in a file.
Code:
string cycle("---NEW CYCLE ");
cycle+=//convert float64 to string and add to cycle
cycle+= "---\r\n";
writeText(cycle.c_str()); //writes string to txt file
Thanks.
The usual way of converting numbers to std::strings is to use std::ostringstream.
std::string stringify(float value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
// [...]
cycle += stringify(data);
You should use sprintf. See documentation here C++ Reference.
As an example it would be something like:
char str[30];
float flt = 2.4567F;
sprintf(str, "%.4g", flt );
Also I would use string::append to add the string. See here .
UPDATE
Updated code according to comment.
You can use sprintf to format the string.

C++ external file read: I know how to find and read a string, findMe. But how do I deal with findMei (finding any number, i, of the string)?

Apologies in advance, because I suspect this may be a silly question.
I have written a function for reading in data from an external file. I then use the data to perform calculations using other code I have written.
The function works by finding a data label that looks like this:
const std::string findMe = "<dataLabel>";
Each time I want to find data, I replace dataLabel with the label of whichever data I need from the file.
Here's what I want to do.
I don't want to have to write in the label of the data I want each time. I want to be able to do this:
for (int i = 0; i < anyNumberOfDataSets; i++)
{
findMe = "<dataLabeli>";
// Then run function for reading in data, put data into a vector.
}
I could then add any number of data sets to my external file, give each one the title
, and have each data set read into a vector.
The problem is, I simply can't figure out how to write findMe = "<dataLabeli>". Is this even possible?
I have tried things like, findMe = "<dataLabel" << i <<, but no luck!
Any suggestions would be much appreciated.
It is very hard to understand what you mean, but I guess you want this
#include <sstream>
#include <string>
for (int i = 0; i < anyNumberOfDataSets; i++)
{
std::ostringstream strm;
strm << "<dataLabel" << i << ">";
const std::string findMe = strm.str();
//...
//proceed with searching findMe
}
You can read more about string streams, for instance, here
you've already got the right answer, so this is just trying to help you with solving such problems in the future:
Your core problem here is to convert the integer i into a string s (if you've done this, than you just do findMe = "<datalabel"; findMe += s; findMe += ">";.
Googling for c++ convert integer into string will give you this as the first result. Problem solved.
This is not saying "use google before/instead of asking", it's rather "try to identify the core problem".
Another solution:
using namespace boost;
findMe = str(format("<dataLabel%d>") % i);
This will substitute %d with the value of i, formatted like printf() does.

Parse int to string with stringstream

Well!
I feel really stupid for this question, and I wholly don't mind if I get downvoted for this, but I guess I wouldn't be posting this if I had not at least made an earnest attempt at looking for the solution.
I'm currently working on Euler Problem 4, finding the largest palindromic number of two three-digit numbers [100..999].
As you might guess, I'm at the part where I have to work with the integer I made. I looked up a few sites and saw a few standards for converting an Int to a String, one of which included stringstream.
So my code looked like this:
// tempTotal is my int value I want converted.
void toString( int tempTotal, string &str )
{
ostringstream ss; // C++ Standard compliant method.
ss << tempTotal;
str = ss.str(); // Overwrite referenced value of given string.
}
and the function calling it was:
else
{
toString( tempTotal, store );
cout << loop1 << " x " << loop2 << "= " << store << endl;
}
So far, so good. I can't really see an error in what I've written, but the output gives me the address to something. It stays constant, so I don't really know what the program is doing there.
Secondly, I tried .ToString(), string.valueOf( tempTotal ), (string)tempTotal, or simply store = temptotal.
All refused to work. When I simply tried doing an implicit cast with store = tempTotal, it didn't give me a value at all. When I tried checking output it literally printed nothing. I don't know if anything was copied into my string that simply isn't a printable character, or if the compiler just ignored it. I really don't know.
So even though I feel this is a really, really lame question, I just have to ask:
How do I convert that stupid integer to a string with the stringstream? The other tries are more or less irrelevant for me, I just really want to know why my stringstream solution isn't working.
EDIT:
Wow. Seriously. This is kind of embarrassing. I forgot to set my tempTotal variable to something. It was uninitialized, so therefore I couldn't copy anything and the reason the program gave me either a 0 or nothing at all.
Hope people can have a laugh though, so I think this question would now be better suited for deletion since it doesn't really serve a purpose unless xD But thanks to everybody who tried to help me!
Have you tried just outputting the integer as is? If you're only converting it to a string to output it, then don't bother since cout will do that for you.
else
{
// toString( tempTotal, store ); // Skip this step.
cout << loop1 << " x " << loop2 << "= " << tempTotal << endl;
}
I have a feeling that it's likely that tempTotal doesn't have the value you think it has.
I know this doesn't directly answer your question but you don't need to write your own conversion function, you can use boost
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
//usage example
std::string s = lexical_cast<std::string>(tempTotal);
Try the following:
string toString(int tempTotal)
{
ostringstream ss;
ss << tempTotal;
return ss.str();
}
string store = toString(tempTotal);
If you want to output the integer, you don't even need to convert it; just insert it into the standard output:
int i = 100;
cout << i;
If you want the string representation, you're doing good. Insert it into a stringstream as you did, and ask for it's str().
If that doesn't work, I suggest you minimize the amount of code, and try to pinpoint the actual problem using a debugger :)
Short answer: your method to convert an int to a string works. Got any other questions?