2013-03-03 99 views
-2
#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 << "\n\n"; 

    /*for(int i = 0; i < here.length(); i++) 
    { 
     sum += atoi(&here[i]); 
    }*/ 

    cout << atoi(&here[0]); 
    cout << atoi(&here[1]); 
    cout << atoi(&here[2]); 
} 

输出:的atoi()只给0结果

10715086071862673209484250490600018105614048117055336074437503883703510511249361 
22493198378815695858127594672917553146825187145285692314043598457757469857480393 
45677748242309854210746050623711418779541821530464749835819412673987675591655439 
46077062914571196477686542167660429831652624386837205668069376 

000 

为什么全0?

+1

我想你不想'atoi'可言,我想你想简单地减去''0 ''(即文本数字零的字符常量)。看起来好像你想要对字符串中的每个数字进行求和。如果是这种情况,你不会希望使用'atoi'。使用'sum + = here [i] - '0';'在你的循环中 – dreamlax 2013-03-03 06:15:17

+0

思考实验:* atoi *返回类型可以表示的最大数量是多少?第二个想法:双精度浮点数可以表示多少个有效数字。 – Digikata 2013-03-03 06:15:39

+0

在我的系统上运行的相同程序给出了3个-1而不是3个零。就像其他人指出的那样,我觉得这是因为错误。 – Tuxdude 2013-03-03 06:17:39

回答

4

走出去的肢体,这里假设你实际上并不想用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' == ??? 
4

这就是std::atoi表示错误的方法。在这种情况下,错误是数组中的数值大于最大可能的整数更大(这在技术上是未定义的行为atoi,但您的实现显然是把它当作任何其他错误)

3

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

已存储在here数量比INT_MAX大,因此atoi返回零:

成功时,该函数将返回转换整数为int值。如果不能执行有效的转换,则返回零值。

编辑:实际上,甚至没有看我自己的链接不够仔细,显然这是在这种情况下

未定义行为上有当转换后的值会发生什么变化没有标准规范超出了可表示值的范围。

www.cplusplus.com

0

这里[0]”返回“这里”的第一个字符为焦炭

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

的std ::的atoi(这里[0])返回这里的第一个字符为,并将其转换为INT ...或者假使“的atoi '处理了字符。它不 - 它处理字符数组。给它一个字符可能不会编译。

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

这意味着,给定字符串 “567321”:

  • 的std ::的atoi(&这里[0])将返回 “987654321”
  • 的std ::的atoi(&这里1)将返回“87654321”
  • 的std ::的atoi(&这里2)将返回 “7654321”
  • 的std ::的atoi(&这里[3])将返回 “654321”
  • ...等等。

    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()); 
    } 
    

    更好的方法是:

如果你真的想总结所有的数字,并要求使用std ::的atoi(),那么你可以使用std::string::substr()做使用方法@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); 
}