解析字符串以获得int
parsing a string to get an int
我必须在程序中读取std::cin中的字符串。cin中的行的格式是两个数字后面跟着一个冒号,另外两个数字前面跟着一个结肠,然后是一条直线。然后,相同的字符串将被重复。一个例子:
00:33:11 | 22:55:22
然后我希望两个int a和b是:a=3311b=222522
我正试图找到最好的方法,从直线前的第一个数字中提取数字,并将其存储到int中,对第二组数字也这样做。
我对c++有点不熟悉,但我考虑过制作一个for循环,将字符存储到一个char数组中,然后在该数组上使用atoi。然而,我觉得这种方法不是最优雅的方法。对这个问题有什么建议吗?
感谢
您可以使用std::istringstream
和std::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;
相关文章:
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 构造<int>具有 2 个字符串文字的向量
- 字符串中int的加法运算
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- cin >> int 给定一个字符串将 int 赋值为 0
- 将字符串中的 int 转换为字母;
- 使用 switch,但我想用字符串而不是 int 进行选择
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- 从字符串流中读取具有特定字段宽度的 int
- win 表单应用程序字符串^ 到 int
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 将字符串转换为 int 后的随机值
- 如何检查字符串是否正确以将其转换为 int?
- 在乌鸦中获取非Int(字符串)URL资源ID
- 如何使 int 字符串中的每个输入都成为一位数
- 将无符号int+字符串强制转换为无符号char向量
- 如何在C++中连接字符串+int+字符串
- 如何在消息框中使用int字符串?
- 如何在C++中将向量转换为<int>字符串