I have a code where i get the input as numbers(comma separted) in string format. I should convert the input string to integer. which i have done it by using
digit[k] = (digit[k]*10)+std::atoi(line[i]);
But i get the error as
jdoodle.cpp: In function 'int main()':
jdoodle.cpp:28:54: error: invalid conversion from 'char' to 'const char*' [-fpermissive]
digit[k] = (digit[k]*10)+std::atoi(line[i]);
The full program is
#include <iostream>
#include<cstdlib>
using namespace std;
int main() {
char line[1024];
int digit[1024],two[1024],k=0,m=0,temp1=0,avg=0;
for(int i=0;i<1024;i++)
{
digit[i]=0;
}
cout << "Enter a line of string: ";
cin.getline(line, 1024);
for(int i = 0; line[i]!='\0'; ++i)
{
if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
{
cout<<"\nInvalid input";
return 0;
}
else if(line[i]>='0' && line[i]<='9')
{
digit[k] = (digit[k]*10)+std::atoi(line[i]);
//++digits;
}
else if (line[i]==',')
{
k=k+1;
}
}
for(int j=0;digit[j]!='\0';j++)
{
int temp=digit[j];
while(temp!=0)
{
temp=temp/10;
count=count+1;
}
if(count==2)
{
two[m]=digit[j];
m=m+1;
count=0;
}
}
for(int i=0;two[i]!='\0';i++)
{
total = total+two[i];
temp1=i;
}
avg=total/temp1;
cout << avg;
return 0;
}
The prototype of atoi:
int atoi (const char * str);
Here you can see atoi
expects a string literal, not a single character. You can change your code
digit[k] = (digit[k]*10)+std::atoi(line[i]);
into
digit[k] = (digit[k]*10)+(line[0] - '0');
to fix this error. What this does is basically convert your single char to an int, without the use of atoi