Atoi()只给出0结果

atoi() only giving 0 result

本文关键字:结果 Atoi      更新时间:2023-10-16
#include <iostream>
#include <math.h>
#include <iomanip>
#include <sstream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
    ostringstream str;
    double num = pow(2,1000);
    int sum = 0;
    str << setprecision(1000) << num;
    string here = str.str();
    cout << here << "nn";
    /*for(int i = 0; i < here.length(); i++)
    {
        sum += atoi(&here[i]);
    }*/
    cout << atoi(&here[0]);
    cout << atoi(&here[1]);
    cout << atoi(&here[2]);
}
输出:

10715086071862673209484250490600018105614048117055336074437503883703510511249361
22493198378815695858127594672917553146825187145285692314043598457757469857480393
45677748242309854210746050623711418779541821530464749835819412673987675591655439
46077062914571196477686542167660429831652624386837205668069376
000

为什么都是0 ?

假设您实际上不想使用std::atoi。如果要对字符串中的每个数字求和,则需要将数字字符转换为其数字。最快的方法是减去字符常数'0'。在循环中,只需使用:

for(int i = 0; i < here.length(); i++)
{
    sum += here[i] - '0';
}

这是可能的,因为从字符串中的各个字符中减去'0'会得到该字符所代表的数值。

'0' - '0' == 0
'1' - '0' == 1
'2' - '0' == 2
//etc
'9' - '0' == 9

就我所记得的,c++标准并没有强制任何特定的编码,但是它确实指定了数字字符必须是连续的,所以当字符串只包含数字时,上面的方法是安全的,对字符串中可能出现的其他字符进行减法会导致结果不正确:

'E' - '0' == ???
'.' - '0' == ???
'+' - '0' == ???

std::atoi就是这样指示错误的。在这种情况下,错误是数组中的数值大于可能的最大整数(这在技术上是未定义的行为atoi,但您的实现显然将其视为任何其他错误)

atoi将字符串转换为整数(在您的平台上可能是32位或64位)。

存储在here中的数字大于INT_MAX,因此atoi返回0:

操作成功时,函数返回转换后的整数值作为整型值。如果不能执行有效的转换,则返回零值。

EDIT:实际上,我甚至没有仔细阅读我自己的链接,显然在这种情况下,这是未定义的行为

对于转换后的值超出int型可表示值的范围会发生什么情况,没有标准规范。

从www.cplusplus.com

这里[0]的返回的第一个字符""作为一个字符

,这里[0]的返回地址这里[0]"。你不会想要地址的。'&'用于获取变量的地址。

std::atoi(here[0])返回 where 的第一个字符作为char,并将char转换为int…或者,如果"atoi"处理字符。它不-它处理字符数组。给它一个字符可能无法编译。

std::atoi(&here[0])可以编译,但不是您想要的。Atoi将继续读取字符,直到到达空字符。

这意味着给定字符串"567321":

  • std::atoi(&here[0])将返回"987654321"
  • std::atoi(&here1)将返回"87654321"
  • std::atoi(&here2)将返回"7654321"
  • std::atoi(&here[3])将返回"654321"

如果您真的想要对所有的数字求和,并且需要使用std::atoi(),那么您可以使用std::string::substr():

for(int i = 0; i < here.length(); i++)
{
    std::string subString = here.substr(i,1); //Returns a substring starting at 'i', and including 1 character 
    sum += atoi(subString.c_str());
}

一个更好的方法是使用方法@dreamlax张贴…但是如果你正在学习字符串和std::atoi,学习std::string::substr()是很重要的。

如果你使用c++ 11,你可以用std::stoi:

重写它
for(int i = 0; i < here.length(); i++)
{
    std::string subString = here.substr(i,1); //Returns a substring starting at 'i', and including 1 character 
    sum += std::stoi(subString);
}