invalid conversion from 'int' to 'const char*' [-fpermissive]| (beginner) - c++

When I try to compile my code this error pops out:
invalid conversion from 'int' to 'const char*'
My task is to write a program that calculates the sum of numbers with odd index.
Please don't roast me (I'm learning how to code in c++), and give some tips how to fix it and get my code working.
#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = len; i > 0; i++) {
a = text[i];
if (i % 2 == 1) {
number = atoi(a);
sum = sum + number;
}
}
cout << sum;
return 0;
}

Your for loop is incorrect because at the first try it starts at out of range index and increases farther. here :
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = 0; i < len; i++) {
a = text[i];
if (i % 2 == 1) {
number = a - '0';
sum = sum + number;
}
}
cout << sum;
return 0;
}

atoi is a function for converting a string to an integer, but a is a character not a string. That's why you have the error.
Replace atoi(a); with a - '0'. That's a formula for converting a digit character to its integer value.

I see a few issues. The most obvious:
number = atoi(a);
atoi expects a const char *, but a is an int.
Note that it would help if you listed which line produces the error message.
Without trying it, I think you can get rid of the atoi() and just do:
sum += a - '0';
The other choice would be to make a into a string and use text.subst() to just get a single character, then you could do:
sum += atoi (a.c_str());
or
sum += stoi(a);
In programming, there are always a dozen of ways to do the same thing.

Learn to extract functions. This will do your task without converting to string.
int sumOfDigitsInEvenPos(int x, int base = 10) {
x = std::abs(x);
int sum = 0;
while (x) {
sum += x % base;
x /= base * base;
}
return sum;
}

There are more than few mistakes :
starting with declaring 'a' as int.
in Your for loop you are starting with length which should be
length-1.
In for loop again you are using i++ which should be i-- or start with i=0;
When you are getting number why you are taking string as input
taking as int/long should be more convient.
atoi accepts char * not int
try out below code it should solve your problem
#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
cin>>text;
int len= text.length();
cout<<len<<endl;
int sum=0,number=0;
char a;
for(int i=len-1;i>0;i--)
{
a=text[i];
if(i%2==1)
{ number= (int)a;
sum = sum+number;
}
}
cout<<sum;
return 0;
}

I think you need to check return code of atoi function, because string consists non only of numeric values.
And length returns size of string, for example 5, but symbols iterates from 0 to 4. text[4] - final symbol.

Related

How to access c++ string by index for a integer number?

How do i edit this program for j to contain "1"?
Currently it shows 49 which is the ascii value i think.
#include <iostream>
using namespace std;
main()
{
string i = "123";
int j = i[0];
cout << j;
}
You can do this as shown below:
int main()
{
std::string i = "123";
int j = i[0] - '0'; //this is the important statement
std::cout << j;
}
Explanation
'0' is a character literal.
So when i wrote:
int j = i[0] - '0';
The fundamental reason why/how i[0] - '0' works is through promotion.
In particular,
both i[0] and '0' will be promoted to int. And the final result that is used to initialize variable j on the left hand side will be the resultant of subtraction of those two promoted int values on the right hand side.
And the result is guaranteed by the Standard C++ to be the integer 1 since from C++ Standard (2.3 Character sets)
...In both the source and execution basic character sets, the value of
each character after 0 in the above list of decimal digits shall be
one greater than the value of the previous.
So there is no need to use magic number like 48 etc.
Construct a new string from character.
Convert the substring to integer.
Example:
#include <iostream>
using namespace std;
main() {
string i = "123";
// Method 1, use constructor
string s1(1, i[0]);
cout << s1 << endl;
// Method 2, use convertor
int j = atoi(s1.c_str());
cout << j << endl;
}
The solution is simple , just cast j to char .
Example:
#include <iostream>
using namespace std;
main()
{
string i = "123";
int j = i[0];
cout << char(j);
}
You have to subtract ASCII '0' (48) from the character digit:
#include <iostream>
using namespace std;
int main()
{
string i = "123";
int j = i[0] - 48; // ASCII for '0' is 48
// or
// int j = i[0] - '0';
cout << j;
}
Change j to be a char instead of an int:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string i = "123";
char j = i[0];
cout << j;
}

how to get large numbers as input?

Hi I'm really new to c++ and I wanted to write a code which receives a number from user and sums its digits and keeps doing that until it gets a one-digit number and returns it as a result. But I noticed that when my number is large (like 15 digits long), the wrong number is stored in the variable i declared for storing user input. What do I do?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int get_sum(long x) {
cout << x<<endl;
if (x < 10) {
return x;
}
else {
string num_in_str = to_string(x);
long result=0;
for (int i = 0; i < num_in_str.size(); i++) {
int digit = num_in_str[i] - '0';
result += digit;
}
return get_sum(result);
}
}
int main()
{
long input;
cin >> input;
int final_result = get_sum(input);``
cout << final_result;
}
Oh I found out. I had to use uint64_t data type
Integer data types in C++ can store numbers up to certain limit. In particular, depending on platform and compiler, "long" can be 32 or 64 bit, and store up to 2^31-1 or 2^63-1. If you want to process numbers of an arbitrary precision, I'd suggest to read each input as string, and process it character-by character, like this:
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::string s;
while (std::getline(std::cin, s)) {
// parse string
long sum = 0;
for (std::size_t i = 0; i < s.length(); ++i) {
if (std::isdigit(s[i]))
sum += s[i] - '0';
else
break;
}
std::cout << sum << std::endl;
if (sum < 10) break;
}
return 0;
}

Recursively convert a given string to the number it represents

Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer.
I only get the first digit of my string as the output. E.g "1234" as 1 or "231" as 2. Which makes me think there may be an error in my recursive function (the base case seems fine though) but I cant figure out what it is.
#include <math.h>
#include <cmath>
#include <iostream>
using namespace std;
int lenght (char input[]){
int count = 0;
for (int i=0 ; input[i] != '\0' ; i++){
count++;
}
return count;
}
//helper
int stringToNumber(char input[], int start ) {
int len = lenght(input);
//base case
if(start ==0){
return int (input[start]) - 48;
}
int a = stringToNumber(input , start+1);
int b = int(input[start]) - 48;
int k = pow(10, len-1);
return k*b + a;
}
int stringToNumber(char input[]) {
return stringToNumber(input, 0);
}
int main() {
char input[50];
cin >> input;
cout << stringToNumber(input) << endl;
}
Sample Input 1 :
1231
Sample Output 1:
1231
What my code generates: 1
Converting string to decimal integer - is actually converting a number from decimal to binary form. I.e. each digit is a mod of 10.
I.e. for the 1234 it can be done done like 1 * 1000 + 2 * 100 + 3 * 10 + 4
or (1*10)+2, (12*10)+3, (123*10)+4. Second algorithm can be implemented like next recursive function:
constexpr uintmax_t atou(const char* a,uintmax_t ret = 0) noexcept {
return '\0' == *a ? ret : atou(a+1, (ret * 10) + ( *a - '0') );
}
i.e. you are scanning a string for digits, until '\0' end of line character (or std::isspace for example), if more digits in the string multiply result on 10 and add the next digit to the result.
static_assert( 1234 == atou("1234"), "1234 expected" );
Try this code:
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
int convert(char c[]) {
if (c[0]=='\0') {
return 0;
} else {
int d = strlen(c) - 1;
int p = pow(10, d);
int k = int(c[0]) - 48; // ASCII value of '0' is 48
return (k * p + convert(c + 1));
}
}
int main() {
int n;
cin >> n;
char c[n];
cin >> c;
cout << convert(c);
}
public class solution {
public static int convertStringToInt(String input){
// Write your code here
if(input.length()<1)
{
return 0;
}
return input.charAt(input.length()-1)-'0'+(10*convertStringToInt(input.substring(0,input.length()-1)));
}
}

C++ convert string with word and number to number

How to convert string like 3 word 12 with word to a int only contain number 312 without using stoi in C++? My Codeblode gave me an error stoi is not a member of std when I tried to use it.
Thank you in advance!
Go through the line and skip non-digit symbols. And for digits use -'0' conversion and *10 shift approach. E.G.:
#include <stdio.h>
#include <ctype.h>
//or cctype to use isdigit()
#include <string.h>
//or cstring to use strlen()
int main()
{
char str[] = "3 word 12 with word"; // can be any string
int result = 0; // to store resulting number
// begin of solution
for (int i = 0; i < strlen(str); i++)
{
if (isdigit(str[i]))
{
result *= 10;
result += str[i] - int('0');
}
}
// end of solution
printf("%d\n", result);
return 0;
}
Same idea as in VolAnd's answer. Just, because the question is tagged c++, using some STL stuff.
#include <iostream>
#include <numeric>
#include <string>
using namespace std;
int main(){
std::string input("3 word 12 with word");
int num = std::accumulate(input.begin(), input.end(), 0,
[](int val, const char elem) {
if (isdigit(elem)) {
val = val*10 + (elem-'0');
}
return val;
}
);
std::cout << num << std::endl;
return 0;
}
see http://en.cppreference.com/w/cpp/algorithm/accumulate
note: It gets slightly more interesting if you want to allow a leading minus sign....
And using boost::adaptors::filter(rng, pred) on this one would be fun but slightly overdoing it ;-)
Assuming that s is your initial string.
int toInt(string s) {
string digits;
for(size_t i = 0; i < s.size(); i++)
if(s[i] >= '0' && s[i] <= '9')
digits.push_back(s[i]);
int res = 0;
for(size_t i = 0; i < digits.size(); i++)
res = res * 10 + digits[i] - '0';
return res;
}
Leading zeros are not a problem.
Note however that it is possible to receive an overflow if the resulting digits string will contain a big number.

Number Reversal in c++

When I pass an odd digit number > 1 to the function, I am getting 1 less than the actual result I should be getting and the code is working perfectly fine for an even digit number, I am not able to figure out why.
int rev_number(int num){
int arr [10];
int i=0;
int j=0;
int rev_num=0;
while(num > 0){
arr[i] = num%10;
num = num/10;
i++;
}
i--;
while(i>=0){
rev_num += arr[j] * pow(10,i);
j++;
i--;
}
return rev_num;
}
You should avoid using pow which return a double while you only want to manipulate integers. For example, imagine if the result of arr[j] * pow(10,i) is 753.99..., the cast would only put 753 in rev_num! In some cases, that will work, but not always. It's a fifty-fifty chance to work.
Try replacing:
rev_num += arr[j] * pow(10,i);
to
rev_num = rev_num * 10 + arr[j];
Have you tried to round or to add .5? Does that also fix your problem?
How about the following simple code
int reverseNumber(int num) {
int reverse = 0;
while(num > 0) {
reverse = reverse*10 + num%10;
num = num/10;
}
return reverse;
}
Since pow deals with floating point values, it's integer representation may get truncated, so certain values may end up being lower than expected.
A better solution is to use integer math, such as this:
while(i>=0){
rev_num *= 10;
rev_num += arr[j];
j++;
i--;
}
There are several other ways to express the same thing, and storing the values in an array isn't strictly necessary, you could just multiply the modulo value back in.
However, my favourite "reverse a number" is to read it in as a string, and then use the standard reverse function.
So, something like this:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
std::reverse(s.begin(), s.end());
std::cout << s << std::endl;
}
All code examples of the function showed here are invalid because the function does not process valid integer 0. So I decided to show a correct function realization.:)
using System;
namespace ReverseNumberExercise
{
class Program
{
static int ReverseNumber(int x)
{
int y = 0;
do
{
long digit;
x = ( int )Math.DivRem( x, 10L, out digit );
y = y * 10 + ( int )digit;
} while ( x != 0 );
return (y);
}
static void Main()
{
while (true)
{
Console.Write("Enter an integral number: ");
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) break;
int x;
if (!int.TryParse(input, out x))
{
Console.WriteLine("Invalid number. Try again.");
}
Console.WriteLine("Reversed number is: {0}", ReverseNumber(x));
Console.WriteLine();
}
Console.WriteLine("\nGood bye!");
}
}
}