【问题标题】:'atoi' function is returns only 2 digit number if I enter a 3 digit character in character array如果我在字符数组中输入 3 位字符,'atoi' 函数仅返回 2 位数字
【发布时间】:2015-03-15 18:43:59
【问题描述】:
#include <iostream>
using namespace std;
int main()
{
    char myarray[3] = {'0','1','2'};
    int i = atoi(myarray);
    cout<<i<<endl;
}

这个节目只有 12 个,但我希望它是 012... 有没有其他功能可以做到这一点?

【问题讨论】:

    标签: arrays integer atoi


    【解决方案1】:

    这有很多问题:

    char myarray[3] = {'0','1','2'};
    

    这错过了NULL 终止符(因此无法确定字符串的结尾在哪里)。从字符串初始化的更简单方法是:

    char myarray[] = "012";
    

    这将为您排序长度并添加 NULL 终止符。

    您没有得到前导零,因为您存储转换结果的类型不知道原始输入数据的长度,或者它有多少前导零......它实际上只是一个数字。如果您还想打印多个前导零,您可以使用iostream.width() 设置最小宽度,并使用iostream.fill() 设置使用哪个字符来填充它,例如

    cout.width(3); // At least three chars
    cout.fill('0');  // Pad with zeroes
    cout << i;
    

    我会质疑为什么你需要能够做到这一点; JuniorCompressor 的答案似乎更符合您当前的需求。

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多