简体   繁体   English

解析字符串以获得整数

[英]parsing a string to get an int

I have to read in a string from std::cin in my program. 我必须从程序中的std :: cin中读取字符串。 The lines from cin are in the format of two numbers followed by a colon, another two numbers followed by a colon, and then a straight line. cin中的线条的格式为:两个数字后跟一个冒号,另外两个数字后跟一个冒号,然后是一条直线。 Then, the same string would be repeated. 然后,将重复相同的字符串。 An example: 一个例子:

00:33:11|22:55:22 00:33:11 | 22:55:22

and then I would want two ints a and b to be: a = 3311 b = 225522 然后我想要两个整数a和b为:a = 3311 b = 225522

I'm trying to find the best way to extract the numbers from the first numbers before the straight line and store that into an int, and do the same for the second set of numbers. 我试图找到最好的方法,从直线之前的第一个数字中提取数字并将其存储到int,然后对第二组数字进行相同的处理。

I'm a little unfamiliar with c++, but I have thought about making a for loop, storing characters into a char array, and then using atoi on that array. 我对c ++有点陌生,但是我已经考虑过要进行for循环,将字符存储到char数组中,然后在该数组上使用atoi。 However, I feel that this method is not the most elegant of approaches. 但是,我觉得这种方法并不是最优雅的方法。 Any suggestions to this problem? 对这个问题有什么建议吗?

thanks 谢谢

You could use std::istringstream and std::getline() to help you with that: 您可以使用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);

    //...
}

Personally, I would use sscanf() instead: 就个人而言,我将使用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;
    //...
}

Try scanning in integers, and scanning and ignoring the separator characters. 尝试扫描整数,然后扫描并忽略分隔符。 Then use some multiplication to get your number. 然后使用一些乘法得到您的数字。 In your case, try this: 在您的情况下,请尝试以下操作:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM