Hey, I have been struggling with a problem on a project Im working on.

I have 3 ints, day, month, year and I want to put them into a string I use for another function to search through a file.

so lets say
day = 20
month = 11
year = 08

I want the string to contain "201108"

Seems like there should be a simple solution to this, but my head is starting to cook over this.

I know I can put 3 strings together by

string a, b, c, d;
a += b;
a += c;
a+= d;

cout "String b + c + d combined: << a << endl;

To use the method above, I need to convert each interger into a string, but every convertion method I find is usually used with a char array. strcat, strcpy, printf, sprintf.

Recommended Answers

All 2 Replies

Here is one way to do it -- use stringstream class

#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char* argv[])
{
    int day = 20;
    int month = 1;
    int year = 8;
    stringstream str;
    str << setw(2) << setfill('0') << year << setw(2) << month << setw(2)<< day;
    cout << str.str() << "\n";
    return 0;
}

Here is one way to do it -- use stringstream class

#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char* argv[])
{
    int day = 20;
    int month = 1;
    int year = 8;
    stringstream str;
    str << setw(2) << setfill('0') << year << setw(2) << month << setw(2)<< day;
    cout << str.str() << "\n";
    return 0;
}

Thank you so much, was exactly what I was looking for :)
Also specially setfull('0') even though I forgot to say it was a problem.

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.