Converting a C string to individual integers - c++

This exercise asks to take a input as a character array of number then add up the digits of the number.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main() {
//Input a series of single digit numbers
char numbers[] = "a";
cout << "Input a series of single digit numbers." << endl;
cin >> numbers;
//convert the character array into a int array.
int sum = 0;
for (int i = 0; i < size; i++) {
sum += atoi(numbers[i]);
}
cout << "Sum of digits: " << sum;
return 0;
}
The atoi function, by my understanding, converts only whole character arrays (C strings) at a time, and I guess I cant step through the array, but it seems like this should work. My other option was to convert the Cstring to one large integer, then use the length of the string to step through and calculate the digits in each position but that's probably more inefficient that I could be making it.
What would you use to find single digits as ints for a character array?

char numbers[] = "a";
This creates an array of 2 char items. That's not sufficient for anything reasonable. Use a std::string instead.
cin >> numbers;
Better use std::getline from the <string> header.
sum += atoi(numbers[i]);
atoi takes a string as argument, not a single char. You want the sum of the digits, not the sum of the number values you get by applying atoi to all right substrings of the specification.
For a digit character ch, the corresponding digit value is ch - '0'.

Related

How to convert string to an int array using stoi() && substr()

im triying to convert an string to an integer and save those numbers into an array, i tried like this
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
int number[5];
string input;
//numbers
cout << "type sonme numbers"<<endl;
cin >> input;
for(int i = 0 ; i<= 4; i++){
number[i] = stoi(input.substr(i,i),0,10);
cout << number[i];
}
return 0;
}
when i run it this error comes out:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
Your first loop is asking for a substring beginning at index 0, with length 0, so you're passing an empty string to stoi. Even if you in fact provided valid inputs (a string of at least eight digits, so you could call .substr(4, 4) on it and get useful results), the first loop always tries to parse the empty string and dies. Don't do that.
It's unclear what the goal here is. If you meant to parse each digit independently, then what you wanted was:
number[i] = stoi(input.substr(i, 1), 0, 10);
which would parse out five sequential length one substrings.

How do I input 2 variables in one line and count them in output?

Out of all activity I've been tasked with, this was by far one of the most challenging one.
I am an IT student, ie a beginner in the C++ language, and so far I've only been taught how to make use of while loops and if conditions. By this, we have to use these two in the following activity:
Count how many of a certain digit is present on a given number.
Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result (see sample input and output for example).
In short, a program that reads the first value and checks how many of this first value is present in the second value.
Supposed Input: 2 1242182
Expected Output: 3
As you can see, it counts how many 2s are present in the second value (1242182). The result is 3 since there are three 2s present in it.
I find it impossible to create a program that can read 2 values in one line just using if conditions and a while loop, but this was given by us from an official programming website.
It should look like this.
#include <iostream>
using namespace std;
int main() {
int v1;
cin >> v1;
if (...) {
....
}
while (...) {
...
}
return 0;
}
Also, no using arrays.
#include <iostream>
using namespace std;
int main() {
int v1, v2;
cin >> v1 >> v2;
}
You need to get the two numbers, and then convert the second one to a string and iterate through that, checking it and incrementing.
#include <iostream>
#include <string>
using namespace std;
int main(){
int number, count, digit;
string num;
cin >> number >> num;
for(int i = 0; i < num.length(); i++){
digit = stoi(num[i]);
if(number == digit){
count++;
}
}
cout << "count: " << count << "\n";
}

Adding to very large numbers using stack

i am a novice to C++ , I was trying to write this program for adding two very large numbers using strings but the program is not working correctly and I can't get what's wrong with it , please help me with this.
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main() {
stack <char> a1;
stack<char> a2;
stack<int> result;
stack<int> temp;
int carry = 0;
string num1;
string num2;
cout << "Enter first number (both numbers should have equal digits)" << endl;
getline(cin, num1);
cout << "Enter second number" << endl;
getline(cin, num2);
for (int i = num1.size()-1; i >= 0; i--) {
a1.push(num1[i]);
a2.push(num2[i]);
}
while (!a1.empty() && !a2.empty()) {
int element = (int)a1.top() + (int)a2.top() + carry;
cout << element;
if (element > 10) {
element %= 10;
carry = 1;
}
result.push(element);
cout << result.top() << endl;
a1.pop();
a2.pop();
}
string abc;
while (!result.empty()) {
temp.push(result.top());
result.pop();
abc += temp.top();
}
cout << abc;
}
I know i have definitely made a logical mistake , but i can't get it , can anyone please guide me?
the following is the output am getting
I was thinking, why stacks should be used. My guess is that you did this, because the numbers must be processed from right to left.
Additionally, you have obiously a challenge with strings with a different length.
But both problems can be solved easily. Let us start with the different length strings.
If 2 strings have a different length, we can pad (fill in) the shorter string with leading `0's. How many leading '0s' do we need to add? Right, the delta of the lengths.
And for inserting characters in a string at a certain position, we have the function insert.
So, the code for that will look like this:
if (numberAsString1.length() < numberAsString2.length())
numberAsString1.insert(0, numberAsString2.length() - numberAsString2.length(), '0');
else
numberAsString2.insert(0, numberAsString1.length() - numberAsString2.length(), '0');
This is rather straightforward.
The result will always be 2 strings with equal length. With entering "1234" and "9", we will get: "1234" and "0009".
This makes the next task easier.
Now that we have 2 equal length strings, we can "add", like we learned in school.
We go from right to left, by starting with the highest possible index of a character in the string. This is always length-1.
For calculating the sum, we need first to subtract the ASCII code for '0' from the characters in the string, because the string contains not integer numbers, but characters. For example "123" consists of '1', '2', '3' and not of 1,2,3.
Suming up is then easy: digit + digit + carry.
The resulting digit is always the sum % 10. And the next carry is always sum / 10. Example 1: 3+5=8 8%10=8 8/10=0. Example 2: 9+8=17 17%10=7 17/10=1.
So, also this is rather simple.
After we worked on all digits of the strings, there maybe still a set carry. This we will then add to the string.
Adding digits will be done in any case using the instert function. Because we want to insert digits on the left side of the resulting string.
So, with working from right to left, using correct indices and the insert function, we do not have the need for a stack.
With a lot of input checking, the whole function would look like this:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
// Give instruction to user
std::cout << "\nPlease enter 2 positive interger numbers:\n";
// Here we will store the user input
std::string numberAsString1{}, numberAsString2{};
// Get strings from user and check, if that worked
if (std::cin >> numberAsString1 >> numberAsString2) {
// Check if all characters in string 1 are digits
if (std::all_of(numberAsString1.begin(), numberAsString1.end(), std::isdigit)) {
// Check if all characters in string 2 are digits
if (std::all_of(numberAsString2.begin(), numberAsString2.end(), std::isdigit)) {
// ---------------------------------------------------------------------------------
// Here we will store the calculated result
std::string result{};
// Temporary helpers
unsigned int carry{};
// ---------------------------------------------------------------------------------
// Make strings equal length. Pad with leading '0' s
if (numberAsString1.length() < numberAsString2.length())
numberAsString1.insert(0, numberAsString2.length() - numberAsString2.length(), '0');
else
numberAsString2.insert(0, numberAsString1.length() - numberAsString2.length(), '0');
// ---------------------------------------------------------------------------------
// Iterate over all digits from right to left
for (int i = numberAsString1.length()-1; i >= 0; --i) {
// Calculate the sum
const int sum = numberAsString1[i]-'0' + numberAsString2[i] - '0' + carry;
// Get the carry bit in case of overflow
carry = sum / 10;
// Save the resulting digit
result.insert(0, 1, sum % 10 + '0');
}
// handle last carry bit
if (carry) result.insert(0, 1, '1');
// ---------------------------------------------------------------------------------
// Show result
std::cout << "\n\nSum: " << result << '\n';
}
else std::cerr << "\n\nError: number 1 contains illegal characters\n";
}
else std::cerr << "\n\nError: number 2 contains illegal characters\n";
}
else std::cerr << "\n\nError: Problem with input\n";
return 0;
}

Concatenating characters of a string in a specific permutation

I am trying to code a C++ program that takes a 5 character long string and then prints out the string with a new permutation with this order: 1st character, 3rd character, 5th character, 2nd character, 4th character. My code is as follows:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string key;
string p10;
cout << "Enter the five characters long string: ";
cin >> key;
p10 = key[0] + key[2] + key[4] + key[1] + key[3];
cout << p10 << endl;’
system(“pause”);
return 0;
}
The output (p10) is a random Greek letter every time I run it.
Please help!
The problem here is that when you use [] on a string, you're not getting back another string, but a single char. A char is actually just a small integer number (think character code), and if you use the + operator with them, it'll add the numbers together. You'll end up with a more or less random character code, which is why you get greek letters.
If you want to keep the structure of the code as close to the original as possible, you can use substr to get "one character strings" instead of plain chars:
key.substr(0, 1) + key.substr(2, 1) + ...
The 1 signifies that you want one character from the specified offset.
Another way is to first construct a char array out of the characters and then turn it into a string:
char p10_arr[] = { key[0], key[2], ... };
string p10(arr, sizeof(arr));
And perhaps the nicest and most concise way is to use the initializer list syntax:
string p10 { key[0], key[2], ... };

Reading character by character to see if it is a digit

I need help with this if statement. Im trying to read each character to see if it is a number. If it is not a digit then say it is not a number if it is continue reading on to the next character. for example if the user inputs 54gr 21 gr42 134 3f3. the only thing that would cout is 21 and 134.
#include <iostream> // libraries
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char string[80];
// char num[80];
// char good[80];
cout << "enter a string "; // prompting user
cin.getline(string,80); // geting line
// int i = 0;
// int j = 0;
int count = 0;
{
while(string[count] != '\0') {
if(string[count] >= '0' && string[count] <= '9' )
cout << count << endl;
}
++ count;
}
}
I would not try to do this character by character. The problem is that you don't now that 5 is really part of a number until you've read to the end of the string of non-space characters to verify that all the contents are legitimately part of a number.
As such, I think you need/want to break the input up into "words", then check whether each complete word can be converted entirely to a number. You can read "words" with just some_stream >> some_string;
Once you have a "word" you check whether you can convert it entirely to a number. Assuming you want integers, you use strtol to (try to) convert it to a number. That will give you a pointer to the first character it couldn't convert as a number. If that's not the end of the string, then that "word" wasn't a number (even if it started with/contained one or more digits).