Reputation: 11
I seem to be having issues removing leading zeroes from an array that is created by the user. For example, the program I am writing will ask the user to input a mathematical expression (input received as a string):
Eg : 1234 + 1234
Before going into creating a function to solve this problem, I can't seem to get my array to ignore the leading zeroes. This is because I am switching the user input from string to integer and then positioning these values at the end of the array (constant size is 20). Below is how I convert from string to an integer array.
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;
}
This is how I tried to remove zeroes:
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];
}
}
Upvotes: 0
Views: 537
Reputation: 935
Another simple approach using C. arr2
contains the array without leading zeros. 48
being the ASCII value for 0
can be used to check for zeros in the given array. However I recommend to use built-in atoi
as suggested by @Ronald.
#include<stdio.h>
int main(){
const char *arr1 = "01234+123";
char *arr2 = (char *)malloc(20);
int i,j=0;
for(i=0; arr1[i] != '\0'; i++){
if((arr1[i] - 48) != 0){
arr2[++j] = arr1[i];
}
}
return 0;
}
Upvotes: 0
Reputation: 2248
There is a better way for converting strings to integers. There is a buildin function called atoi()
in C++. You will have to use stdlib.h
header file for this. Converting character array to integer using this function will automatically remove unwanted values in the array.
#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;
}
Hope it helped. Ask if you need any help.
Upvotes: 2