converting "string" to "int" with a "/" between it
I want to the user to type in the current date like, for example:
25/05/2011
(everythin开发者_开发知识库g together, just separated with a /
)
Then I want to separate this input into 3 int
variables. D
is the Day, M
is the month and Y
is the year.
Here's what I've got so far:
#include <iostream>
using namespace std;
string TOGETHER;
int D, M, Y;
int main()
{
cin >> TOGETHER;
/*
What should I do here?
*/
cout << "\n";
cout << D << "/" << M << "/" << Y << "\n";
return 0;
}
You could give scanf
a try. Or cin
followed by sscanf
.
You can either use sscanf
on TOGETHER.c_str()
, or use atoi
and break the string to substrings with '/' as the delimiter using TOGETHER.find
or similar.
Or you can just do the input using scanf
, but this is not advised (harder to verify valid input).
You should use Boost:
std::vector<string> DMY;
boost::split (DMY, TOGETHER, boost::is_any_of("/"));
D = boost::lexical_cast<int>(DMY[0]);
M = boost::lexical_cast<int>(DMY[1]);
Y = boost::lexical_cast<int>(DMY[2]);
Here it is (read the comments for explanations):
#include <iostream>
#include <string>
// Converts string to whatever (int)
// Don't worry about the details of this yet, focus on use.
// It's used like this: int myint = fromstr<int>(mystring);
template<class T>
T fromstr(const std::string &s)
{
std::istringstream stream(s);
T t;
stream >> t;
return t;
}
std::string TOGETHER;
int D, M, Y;
int main()
{
std::string temp;
int pos = 0;
int len = 0;
// Get user input
std::cin >> TOGETHER;
// Determine length
for(len = 0; TOGETHER[len] != '/'; len++)
;
// Extract day part from string
temp = TOGETHER.substr(pos, len);
// Convert temp to integer, and put into D
D = fromstr<int>(temp);
// Increase pos by len+1, so it is now the character after the '/'
pos += len + 1;
// Determine length
for(len = 0; TOGETHER[len] != '/'; len++)
;
// Extract month part from string
temp = TOGETHER.substr(pos, len);
// Convert temp to integer, and put into M
M = fromstr<int>(temp);
// Increase pos by len+1, so it is now the character after the '/'
pos += len + 1;
// Determine length
for(len = 0; TOGETHER[len] != '/'; len++)
;
// Extract year part from string
temp = TOGETHER.substr(pos, len);
// Convert temp to integer, and put into Y
Y = fromstr<int>(temp);
std::cout << "\nDate:\n";
std::cout << "D/M/Y: " << D << "/" << M << "/" << Y << "\n";
std::cout << "M/D/Y: " << M << "/" << D << "/" << Y << "\n";
return 0;
}
See that repetitive code in the middle? It could easily (and should've) have been put into it's own function, which would make this way more awesome. I'll leave that to you. :)
Step 1 : Split the String using "/" and strore it in an vector
split( strLatLong , '|' , Vec_int) ; //Function to call
std::vector<std::int> split(const std::string &s, char delim, std::vector<int> &elems)
{
std::stringstream ss(s);
int item;
while(std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
cout << vec_int[0]<<vec_int[1]<<vec_int[2];
精彩评论