0

I was trying to solve a problem. The Problem is : There is given a date string like 21/9/2013. I have to convert this date into int. I have used stoi but it is just showed first two int 21.

2 Answers2

1

What you want to do here is tokenize the string into three different substrings ("21", "9", and "2013"); then you can call stoi() on each substring and print out the integer stoi() returned for each one.

There are various ways to tokenize a string in C++; rather than choose one to repeat here, I'll just link to the StackOverflow question and answers on that topic.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
1

I want to print 21 9 2013 to the console

So you don't really need three integers. You need three strings.

With these includes:

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

You can parse a string like this:

string date = "21/9/2013";

into its components, like this:

stringstream stream(date);
string s;
while (std::getline(stream, s, '/') {
    cout << s << " ";
}
cout << endl;

The above should print out: 21 9 2013

If you really want integers, the above shouldn't be too hard to modify. You can use stoi on each iteration of the while loop above.

selbie
  • 100,020
  • 15
  • 103
  • 173