c++ - 从数组中删除前导零

标签 c++ arrays function

我似乎无法从用户创建的数组中删除前导零。例如,我正在编写的程序将要求用户输入一个数学表达式(以字符串形式接收的输入):

例如:1234 + 1234

在创建一个函数来解决这个问题之前,我似乎无法让我的数组忽略前导零。这是因为我将用户输入从字符串切换为整数,然后将这些值定位在数组的末尾(恒定大小为 20)。下面是我如何从字符串转换为整数数组。

void stringToInt(int arr[], string value1, int SIZE){
    for (int i = 0; i < SIZE; i++){
         if (arr[i] < 0)
             arr[i] = 0;
         arr[SIZE - 1 - i] = value1[value1.length() - 1 - i] - 48;
}

这就是我尝试删除零的方式:

void removeLeadZeroes(int arr[], string value1, int SIZE){
    bool print = true;
    int carry = 0;
    for (int i = 0; i < (SIZE - 1); i++){
        if (arr[i] == 0
            print = false;
        if (print)
            cout << arr[i];
    }
}

最佳答案

有一种更好的方法可以将字符串转换为整数。在 C++ 中有一个名为 atoi() 的内置函数。为此,您必须使用 stdlib.h 头文件。使用此函数将字符数组转换为整数将自动删除数组中不需要的值。

#include <iostream>
#include <stdlib.h>
using namespace std;

int main() {

    //The character array
    char a[3];

    //The integer variable
    int b;
    gets(a);

    //Converts to integer
    b=atoi(a);

    //To prove that value is an integer and 
    //mathematical operations can be done on it
    cout<<b+2;
    return 0;
}

希望对您有所帮助。询问您是否需要任何帮助。

关于c++ - 从数组中删除前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43177123/

相关文章:

c++ - 为多维字符串动态分配内存

javascript - Angular Controller 阵列错误

php - 额外的0从哪里来

c++ - 在编译时为运行时设置环境变量

c++ - 双探测哈希表

c++ - 按值调用时的隐式转换和多态性

arrays - 仅查询嵌套数组中的数字

java - 如何检查一个int数组是否是一个循环排序的数组?

C++ 在 main 中调用打印 map 的函数时出现问题

C++专门化模板类函数而无需重复代码