解析字符串以获得int

parsing a string to get an int

本文关键字:int 字符串      更新时间:2023-10-16

我必须在程序中读取std::cin中的字符串。cin中的行的格式是两个数字后面跟着一个冒号,另外两个数字前面跟着一个结肠,然后是一条直线。然后,相同的字符串将被重复。一个例子:

00:33:11 | 22:55:22

然后我希望两个int a和b是:a=3311b=222522

我正试图找到最好的方法,从直线前的第一个数字中提取数字,并将其存储到int中,对第二组数字也这样做。

我对c++有点不熟悉,但我考虑过制作一个for循环,将字符存储到一个char数组中,然后在该数组上使用atoi。然而,我觉得这种方法不是最优雅的方法。对这个问题有什么建议吗?

感谢

您可以使用std::istringstreamstd::getline()来帮助您:

#include <string>
#include <sstream>
#include <iomanip>
int timeStrToInt(const std::string &s)
{
    std::istringstream iss(s);
    char colon1, colon2;
    int v1, v2, v3;
    if ((iss >> std::setw(2) >> v1 >> colon1 >> std::setw(2) >> v2 >> colon2 >> std::setw(2) >> v3) &&
        (colon1 == ':') && (colon2 == ':'))
    {
        return (v1 * 10000) + (v2 * 100) + v3;
    }
    // failed, return 0, throw an exception, do something...
}
void doSomething()
{
    //...
    std::string line = ...; // "00:33:11|22:55:22"
    std::istringstream iss(line);
    std::string value;
    std::getline(iss, value, '|');
    int a = timeStrToInt(value);
    std::getline(iss, value);
    int b = timeStrToInt(value);
    //...
}

就我个人而言,我会使用sscanf()来代替:

#include <cstdio>
std::string line = ...; // "00:33:11|22:55:22"
int v1, v2, v3, v4, v5, v6;
if (std::sscanf(line.c_str(), "%02d:%02d:%02d|%02d:%02d:%02d", &v1, &v2, &v3, &v4, &v5, &v6) == 6)
{
    int a = (v1 * 10000) + (v2 * 100) + v3;
    int b = (v4 * 10000) + (v5 * 100) + v6;
    //...
}

尝试扫描整数,扫描并忽略分隔符。然后用乘法运算得到你的数字。在你的情况下,试试这个:

int a;
char b;
int result = 0;
cin >> a;
result += a*10000;
cin >> b;
cin >> a;
result += a*100;
cin >> b;
cin >> a;
result += a;