将“string”转换为“int”,其间带有“/”

时间:2011-04-05 00:21:37

标签: c++

我希望用户输入当前日期,例如:

25/05/2011

(一切都在一起,只用/分开)

然后我想将此输入分成3个int个变量。 D是日,M是月份,Y是年份。

这是我到目前为止所得到的:

#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;
}

5 个答案:

答案 0 :(得分:2)

您可以尝试scanf。或cin后跟sscanf

答案 1 :(得分:1)

您可以在sscanf上使用TOGETHER.c_str(),也可以使用atoi并使用TOGETHER.find或类似内容将字符串转换为使用'/'作为分隔符的子字符串。

或者您可以使用scanf进行输入,但不建议这样做(更难以验证有效输入)。

答案 2 :(得分:1)

您应该使用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]);

答案 3 :(得分:1)

这是(阅读说明的评论):

#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;
}

在中间看到重复的代码?它可以轻松(并且应该)被放入它自己的功能中,这将使这种方式更加棒极了。我会留给你的。 :)

答案 4 :(得分:0)

步骤1:使用“/”拆分字符串并将其存储在矢量

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];