将 STR 转换为 int 的简单方法?C++

easy method for converting str to int? c++

本文关键字:简单 方法 C++ int STR 转换      更新时间:2023-10-16

我正在尝试将字符串转换为整数。我记得一位老师说,你必须从中减去48,但我不确定,当我这样做时,我得到17作为A的值,如果我是正确的64。这是我的代码。任何更好的方法将不胜感激。

#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    string str;
    getline(cin,str);
    cout << str[0] - 48;
    getch();
}

仅使用C++设施的简单且类型安全的解决方案是以下方法:

#include <iostream>
#include <sstream>
int fromString(const std::string& s)
{
  std::stringstream stream;
  stream << s;
  int value = 0;
  stream >> value;
  if(stream.fail()) // if the conversion fails, the failbit will be set
  {                 // this is a recoverable error, because the stream
                    // is not in an unusable state at this point
    // handle faulty conversion somehow
    // - print a message
    // - throw an exception
    // - etc ...
  }
  return value;
}
int main (int argc, char ** argv)
{
  std::cout << fromString ("123") << std::endl; // C++03 (and earlier I think)
  std::cout << std::stoi("123") << std::endl; // C++ 11
  return 0;
}

注意:在fromString()中,您可能应该检查字符串的所有字符是否实际上构成了有效的整数值。例如,GH1234或其他东西不会,并且在调用 operator>> 后值将保持 0 。

编辑:刚刚记住,检查转换是否成功的一种简单方法是检查流的failbit。我相应地更新了答案。

A不是

数字,那么如何将其转换为整数呢?您的代码已经工作。例如,输入 5,您将看到5作为输出。当然,这没有任何区别,因为您只是打印该值。但是你可以存储在一个int变量中:

int num = str[0] - 48;

顺便说一句,通常使用'0'而不是48(48是0的ASCII码)。所以你可以写str[0] - '0'.

有一个atoi函数可以将字符串转换为 int,但我猜你想在没有库函数的情况下这样做。

我能给你的最好的提示是看一下 ascii 表并记住:

int c = '6';
printf("%d", c); 

将打印 ascii 值"6"。

cstdlib 中有一个名为 atoi 的函数,它做的非常简单:http://www.cplusplus.com/reference/cstdlib/atoi/

int number = atoi(str.c_str()); // .c_str() is used because atoi is a C function and needs a C string

这些函数的工作方式如下:

int sum = 0;
foreach(character; string) {
    sum *= 10; // since we're going left to right, if you do this step by step, you'll see we read the ten's place first...
    if(character < '0' || character > '9')
         return 0; // invalid character, signal error somehow
    sum += character - '0'; // individual character to string, works because the ascii vales for 0-9 are consecutive
}

如果你给出"23",它就会变成 0 * 10

= 0。 0 + '2' - '0' = 2。

下一个循环迭代:2 * 10 = 20。 20 + '3' - '0' = 23

做!