【问题标题】:converting string to int in a literal sense从字面意义上将字符串转换为 int
【发布时间】:2016-11-16 17:58:50
【问题描述】:

你好 :) 我正在尝试使用 c++ 将字符串转换为 int。 我曾尝试使用 stol、stoll 和 strtol 函数,并且(也许我使用错了)但它们似乎并没有从字面意义上保留我的字符串。

问题:我将如何将包含 0 和 1 的字符串逐字转换为 int,以便我的 int 与我的字符串完全一样

例子:

string s = "00010011";
int digits = 0; // convert int to: digits = 00010011;

欣赏!

【问题讨论】:

  • int 存储数值。 10011010011 是相同的值。你所描述的实际上是存储一个字符串......所以坚持你的字符串
  • 从 string -> int -> string 开始时,您可能无法保留前导 0。您提到的任何解析函数都可以在合理范围内创建字符串的整数表示。
  • @OldProgrammer 不是重复的,在您的链接中提出问题的人正在询问从字符串到二进制的转换。
  • 实际数字(例如 int)没有前导零,因此它可能看起来不像您想要的那样。如果您不了解整数(除了零本身)不能以零开头,那么您可能应该在编写代码之前学习有关基本数字和数学技能的教程。

标签: c++ string int type-conversion


【解决方案1】:

嗯,你可以使用std::bitset

string s = "00010011";
int digits = 0; // convert int to: digits = 00010011;

std::bitset<32> bst(s);
digits = static_cast<int>(bst.to_ulong());

要对尺寸更加迂腐,而不是std::bitset&lt;32&gt;,您可以这样做:

std::bitset<(sizeof(int) * 8)> bst(s);

要取回字符串(嗯,不完全是)

std::string sp = std::bitset<32>(digits).to_string();

此外,要从sp 中删除前导零:

auto x = sp.find_first_not_of('0');
if(x != string::npos)
    sp = sp.substr(x);

【讨论】:

  • 您好,感谢您的回复。我会考虑尝试你的方法:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 2011-03-06
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
相关资源
最近更新 更多