字符串转换为C++中的整数
String into integer in C++
我有这样的字符串值:2014-04-14
我想把它转换成像这样的整数20140414
我知道Integer中的字符串可以像这个一样完成
std::string myString = "45";
int value = atoi(myString.c_str()); //value = 45
但我不知道如何删除-
符号。
您可以使用std::remove和std::vector#erase:的组合
myString.erase(std::remove(myString.begin(),myString.end(),'-'),myString.end(());
此代码删除-
。
使用流:
std::istringstream iss("2014-04-14");
然后,如果你有C++11,你可以使用新的get_time
io操纵器:
std::tm tm;
if (iss >> get_time(&tm, "%Y-%m-%d"))
...
std::tm
结构具有提取的值,即:
- 年自1900年以来存储在
tm.tm_year
中 - 自1月以来的月份(so 0..11)存储在
tm.tm_mon
中 tm.tm_mday
中存储的月份(1..31)的日期
所以,你想要的价值是:
int value = (tm.tm_year + 1900) * 10000 + (tm.tm_mon + 1) * 100 + tm.tm_mday;
或者,使用C++03,您可以自己解析istringstream
中的值:
int year, month, day;
char c;
if (iss >> year >> c && c == '-' &&
iss >> month >> c && c == '-' &&
iss >> day)
{
int value = year * 10000 + month * 100 + day;
... use value ...
}
else
std::cerr << "invalid daten";
暴力方法:
const std::string text_date = "2014-04-25";
std::string text_no_dash;
for (unsigned int i = 0; i < text_date.length; ++i)
{
if (text_date[i] != '-')
{
text_no_dash += text_date[i];
}
}
此代码显示了仅将所需字符从字符串复制到新字符串的算法。
你试过用这个吗?这就是我过去删除任何我不需要的符号的方式。
char characters[] = "*()$-";
for (unsigned int i = 0; i < strlen(characters); ++i)
{
stringName.erase (std::remove(stringName.begin(), stringName.end(), characters[i]), stringName.end());
}
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- 如何在C++中将整数转换为其数字数组