字符串转换为C++中的整数

String into integer in C++

本文关键字:整数 C++ 转换 字符串      更新时间:2023-10-16

我有这样的字符串值: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());
}