char(string) to integer - c++

I was wondering how to compare one array into two arrays but with some rules:
In my code I need to type 8 digits to make the cycle - OK, I did it. Now I need to compare the array = m[3] to two different arrays:
first array must be with (if m[i]%2==0) ...
second array must be with (if m[i]%2!=0) ...
So if I type from keyboard those three rows in my Main array (m[3]):
12345678
12345689
12344331
After typing them, I need to set the in those two different arrays and here I think I need to make the char(string) to integer to make the check with %, or to somehow do the check only on the last digit (it will work the same way).
So here goes the next step after typing the 3 rows:
arrA=12345678
arrB=12345689 12344331
#include <iostream>
#include <conio.h>
#include <string>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
int main()
{
int i,n;
char m[3];
for(i=1; i<=3; i++)
{
cout<<i<<". Fak nomer: "<<endl;
do
{
cin>>m[i];
gets(m);
}
while (strlen(m)!=7);
cout<<"As integer: "<<atoi(m);
}
}

From what I understand, you are trying to read three positive integers into an array called m, but you want to ensure the following:
all three number have eight digits
the first number (m[0]) is even
the second number (m[1]) is odd
It would be a lot easier if m can be an array of integers, then a conversion from a string to an int is not required. To read the three integers from the console, use this:
// m is now an array of integers
int m[3];
// loops from m[0] to m[2]
for(int i = 0; i < 3; i++)
{
cout<<i<<": "<<endl;
do
{
cin>>m[i];
}
while (!(m[i] >= 1e7 && m[i] < 1e8));
// m[i] must be greater than or equal to 10000000 and less than 100000000
// before continuing
}
By making m an array of integers, checking for even or odd becomes easier:
if (m[0] % 2 == 0)
cout << "m[0] is even" << endl;
if (m[1] % 2 != 0)
cout << "m[1] is odd" << endl;

not sure if i understand your problem, but why not just change
char* m[3];
to
int m[3];
you'd probably want to redo the loop
int m[3];
for(i=0; i<3; i++)
{
cout<<i+1<<". Fak nomer: "<<endl;
cin>>m[i];
while (m[i] < 1000000 || m[i] >9999999)
{
cout<<"number is less/more than 7 digits. Try again:"<<endl;
cin>>m[i];
}
cout<<"As integer: "<< m[i];
}

It is difficult to understand exactly what you're trying to achieve.
If I understand it correctly, you're trying to get 3 7-character input strings (of integers) from the user, and then check each integer of the first string in turn against the same position character in the other 2 strings?
#include <iostream>
#include <string>
int main()
{
std::string m[3];
for(int i = 0; i < 3; ++i)
{
std::cout << i + 1 << ". Fak nomer: "<< std::endl;
do
{
std::cin >> m[i];
}
while (m[i].size() != 7);
}
// we have enforced each string to be 7 characters long, check each character in turn
for(int i = 0; i < 7; ++i)
{
// get the i'th character of each string, and subtract the ascii '0' character to convert to an integer
int a1 = m[0][i] - '0';
int a2 = m[1][i] - '0';
int a3 = m[2][i] - '0';
std::cout << "checking " << a1 << " against " << a2 << " and " << a3 << std::endl;
if (a1 % a2 == 0)
std::cout << a1 << " % " << a2 << " == 0" << std::endl;
if (a1 % a3 != 0)
std::cout << a1 << " % " << a3 << " != 0" << std::endl;
}
return 0;
}

Related

How can I get multiple numbers from a user and add even numbers together and multiply odd numbers?

I want to write a program that takes 5 inputs and adds even numbers and multiplies odd numbers, but I do not know how to do this after I know which number is odd and which is even.
#include<iostream>
using namespace std;
int main(){
int a, b, c, d, e, sum1, sum2, sum3, sum4, sum5, sum6, sum7, sum8, sum9, sum10;
cout<<"Please Enter 5 Integers\t:\t";
cin>>a>>b>>c>>d>>e;
if(a%2==0 && b%2==0)
{
cout<<a+b;
sum1 = a+b;
}
if(a%2==0 && c%2==0)
{
cout<<a+c;
sum2 = a+c;
}
if(a%2==0 && d%2==0)
{
cout<<a+d;
sum3 = a+d;
}
if(a%2==0 && e%2==0)
{
cout<<a+e;
sum4 = a+e;
}
if(b%2==0 && c%2==0)
{
cout<<b+c;
sum5 = b+c;
}
if(b%2==0 && d%2==0)
{
cout<< b+d;
sum6 = b+d;
}
if(b%2==0 && e%2==0)
{
cout<<b+e;
sum7 = b+e;
}
if(c%2==0 && d%2==0)
{
cout<< c+d;
sum8 = c+d;
}
if(c%2==0 && e%2==0)
{
cout<<c+e;
sum9 = c+e;
}
if(d%2==0 && e%2==0)
{
cout<<d+e;
sum10 = d+e;
}
return 0;
}
You don't need all of those variables, and you certainly do not need to check every combination of variables one at a time. A simple loop will suffice.
Try something more like this:
#include <iostream>
using namespace std;
int main(){
int number, sum = 0, product = 1;
cout << "Please Enter 5 Integers\t:\t";
for(int i = 0; i < 5; ++i)
{
cin >> number;
if (number % 2 == 0)
sum += number;
else
product *= number;
}
cout << sum << ' ' << product << endl;
return 0;
}
This is a very rough and relatively simple solution. It throws an exception if the input is not convertible to an int. And since the exception is not caught anywhere, the program exits if the user enters invalid input.
std::vector is roughly the same as an array. It spares you from having to declare 5 variables, and instead stores all the input values in the vector.
The stoi() function converts a string to an integer (stoi = string to integer).
#include <iostream>
#include <vector>
#include <string>
int main() {
bool outputSum, outputProduct = false;
std::vector<int> input;
for (int i = 0; i < 5; i++) {
std::string entered_string;
int entered_value = 0;
std::cout << "Please enter a number: ";
std::cin>>entered_string;
entered_value = stoi(entered_string);
input.emplace_back(entered_value);
}
int sum = 0;
int product = 1;
for (int i = 0; i < 5; i++) {
if (input[i] % 2 == 0) {
sum += input[i];
outputSum = true;
} else {
product *= input[i];
outputProduct = true;
}
}
if (outputSum) {
std::cout << "Sum: " << sum << std::endl;
}
if (outputProduct) {
std::cout << "Product: " << product << std::endl;
}
return 0;
}
I am assuming that you do not want to add the sum and the product at the end, since you didn't specify what exactly you want your output to be.
Understanding of loops makes this code very simple. You store the five numbers, but they're disconnected from each other since they're stored in separate variables. Now you have to write the many tests that you have, and it's a big mess and you feel like there has to be an easier way.
As other answers show, if you don't need to use the numbers later, then you don't need five variables for input; one is sufficient. You store the input into a variable, check if it's even/odd, and update the sum or product variable accordingly. The repetition of a loop makes this work.
If you need to display the numbers or otherwise keep them around for other purposes, an array (or std::vector in this case) comes in handy.
The code below demonstrates a C++ Standard Library function (std::reduce()) that can generate the sum or the product. Other answers do a fine job showing how to calculate those values manually. And just to re-iterate, this solution would be considered viable only if you needed the numbers for some other task.
#include <functional> // std::multiplies
#include <iostream>
#include <numeric> // std::reduce
#include <vector>
void print_container(std::vector<int> v) {
for (auto i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
constexpr int numInputs = 5;
std::vector<int> evenNums;
std::vector<int> oddNums;
for (int tmp, i = 0; i < numInputs && std::cin >> tmp; ++i) {
tmp & 1 ? oddNums.push_back(tmp) : evenNums.push_back(tmp);
}
int sum = std::reduce(evenNums.begin(), evenNums.end(), 0);
int product = std::reduce(oddNums.begin(), oddNums.end(), 1,
std::multiplies<int>());
std::cout << "Even numbers: ";
print_container(evenNums);
std::cout << "Odd numbers: ";
print_container(oddNums);
std::cout << "Sum of evens: " << sum << "\nProduct of odds: " << product << '\n';
}
Output (with input being 1 2 3 4 5):
Even numbers: 2 4
Odd numbers: 1 3 5
Sum of evens: 6
Product of odds: 15

Skip Dublicate Integers

I'm trying to create a program that would ask the person to write 10 integers, the program should print out the integers that has not already been written, meaning it skips the duplicate integers. I know that I'm supposed to have another for loop but how am I supposed to write it?
If I would write "10, 5, 6, 5, 9, 5" it would print out "10, 5, 6, 9"
This is my current code.
int main()
{
const int target = 10;
int num[target];
cout << "Write " << target << " integers by space: ";
for (size_t i = 0; i < target; i++)
{
cin >> num[i];
cout << "[" << num[i] << "]"
<< " ";
}
};
The output is the same as the input. It never skips the same duplicate.
Some people tell me to use a nested for loop and have something like this, but I don't know how to implement it.
for (int i = 0; i < num.size(); i++) {
if (i > 0 && num[i - 1] == num[i]);
cout << num [I] << " ";
}
The easy way to do it is use both a std::unordered_set and a std::vector. The unordered_set can be used as the logic for determining whether the input is unique. If it is just add it to your vector.
A short example (with minimal input error handling) would be:
#include <iostream>
#include <unordered_set>
#include <vector>
#include <limits>
int main (void) {
std::vector<int> vi{}; /* vector of int to preserve order */
std::unordered_set<int> us{}; /* set for ensuring only unique ints */
int i = 0, n = 5;
std::cout << "enter " << n << " integers\n";
while (i < n) {
int tmp;
std::cout << " " << i+1 << ") "; /* prompt for input */
if (std::cin >> tmp) { /* validate EVERY input */
if (us.find(tmp) == us.end()) { /* if tmp not in set */
us.insert(tmp); /* insert tmp in set */
vi.push_back(tmp); /* insert tmp in vector */
}
i++; /* only increment on good input */
}
else { /* handle error */
std::cerr << " error: invalid\n"; /* display error */
std::cin.clear(); /* clear stream state */
/* clear all characters to end of line */
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
std::cout << "\nunique integers\n";
for (const auto& v : vi)
std::cout << " " << v;
std::cout << '\n';
}
Example Use/Output
$ ./bin/vector_unique_int
enter 5 integers
1) 2
2) bananas
error: invalid
2) 4
3) 5
4) 2
5) 4
unique integers
2 4 5
Look things over and let me know if you have questions.
I managed to solve it by using bool. I still don't know how I would write it in another way, please if there is provide me with another solution.
int main()
{
const int target = 10;
int num[target];
cout << "Write " << target << " integers by space: ";
for (int i = 0; i < target; i++)
{
cin >> num[i];
bool unique = true;
for (int j = 0; j < i; j++)
if (num[j] == num[i])
{
unique = false;
break;
}
if (unique)
cout << "[" << num[i] << "]"
<< " ";
}
return 0;
}
Output Was :
Write 10 integers by space: 10 5 10 3 2 5 1 10 9
[10] [5] [3] [2] [1] [9]

Combining array elements in order to assign to a variable in C++

I am kinda a newbie in C++ and I am a having hard time with a situation.
My task is to create a decimal to [2:9] number system conversion. I am dividing the input number to the base and then, taking the quotient as the divident and continuing the same process.
For example if the decimal number is 149 and that number is calculated on base 2, my output is like this:
Remainder 1
Remainder 0
Remainder 1
Remainder 0
Remainder 1
Remainder 0
Remainder 0
Remainder 1
The outputs are the elements of an array named remainder.
And then I have to merge these array elements in reverse order (1001010) to form the new base number as an integer. How can I do this? I am stuck at this point. The above output is just the part of my output. The number will be prompted from user and it is going to be calculated on bases from 2 to 9. So, array lenghts may change (I have the code for the digit calculation, I have no issues with that).
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int merge(int a[]);
int main(int argc, char*argv[])
{
int dNumber;
int system[8];
for (int i = 0; i < 8; i++)
{
system[i] = i + 2;
}
cout << "Please enter the decimal base number which you want to use in the conversion: " << endl;
cin >> dNumber;
int permanent = dNumber; //to keep the input number intact as it changes through the loops (used in line 53)
int ndigits[8]={1};
for (int i = 0; i < 8; i++)
{
while(dNumber > pow(system[i], ndigits[i]))
{
ndigits[i] ++;
}
}
int dNumberNew = dNumber;
for (int k = 0; k < 8; k++){
for (int i=0; i>=0; i++)
{
int Remainder[i], quotient[i];
Remainder[i] = dNumberNew % system[k];
quotient[i] = dNumberNew / system[k]; // since the variables are integers, this line does not assign decimals and finds the quotient easily.
cout << dNumberNew << " " << system[k] << "'e bolundu. " << "Sonuc " << quotient[i] << " Kalan " << Remainder[i] << " cikti." << endl;
dNumberNew = quotient[i];
if (quotient[i] == 0)
{
break;
}
}
cout << "(" << dNumber << ")" << "_(" << system[k] << ")" << "=" << endl;
cout << "" << endl;
dNumberNew = permanent;
}
}
Here is a function you can use as DecimalToBinary converter, analyze the code yourself
string toBinary(unsigned long long* arr, unsigned long long size) {
string answer;
for (unsigned long long i = 1; i < size; i++) {
string binaryNum = "";
while (arr[i] >= 1) {
binaryNum = static_cast<char>((arr[i] % 2) + '0') + binaryNum;
arr[i] = arr[i] / 2;
}
answer += binaryNum + " ";
}
return answer;
}

sort and show the number of digits

I want to my program can sort the inputted integer and compute the number of any integer that inputted and I don't know where should write the cout of c
example
a[9]={2,3,2,6,6,3,5,2,2}
the number of 2 is 4
the number of 3 is 2
the number of 6 is 2
.
.
please fix this code
int main()
{
cout << "please enter the number of digites :" << endl;
int n;
cin>>n;
int a[n];
cout<<"enter numbers :"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
int c;
for(int m=0;m<n;m++)
{
if(a[m]==a[m+1])
c++;
else
c=0;
}
return 0;
}
Read through my solution, I've commented the parts I've changed. I tidied it up a little.
To answer your question: you should print the output (frequency of an integer in array) before you reset the count variable to 1. This will work because we have sorted the array, and will not have to look ahead for more occurrences of the current number.
[EDIT] I also added this above your code:
#include <iostream>
#include <vector>
using namspace std;
Full Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Get input
int n;
cout << "Please enter the number of digits: ";
cin>>n;
vector<int> a;
cout << "Enter " << n << " numbers: " << endl;
for(int i=0;i<n;i++) {
int temp;
cin >> temp;
a.push_back(temp);
}
// Sort input
int i,j;
for (i = 0; i < a.size(); i++) {
for(j = 0; j < a.size()-i-1; j++) {
if(a[j] > a[j+1]) {
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
// If an element is in an array
// we can not have 0 occurrences
// of that element, hence count
// must start at 1
int count = 1;
// Int to count
int current = a[0];
// Ouput if we have reset the count,
// or if it is the last iteration
bool output;
// Loop through array
for (int i = 1; i < a.size(); i++) {
output = false; // Reset output if we have printed
if (a[i] == current) {
// If current int and the element next to it are the same,
// increase the count
count++;
} else {
// If current and next are different,
// we need to show the frequency,
// and then reset count to 1
cout << current << " occurs " << count << " times" << endl;
count = 1;
current = a[i];
}
}
// Output one last time, for last int in sorted set
cout << current << " occurs " << count << " times" << endl;
return 0;
}
If this doesn't help, go and read this page, it is a solution in C, but can be adapted to C++ easily. https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html This will help you understand and write the task. They take you step-by-step through the algorithm.
This is a typical use-case for a std::map. A std::map<char,int> lets you easily count the frequency of charaters (its easier to treat the user input as characters instead of converting it to numbers).
This is basically all you need:
#include <iostream>
#include <iterator>
#include <map>
int main(){
std::istream_iterator<char> it( std::cin );
std::istream_iterator<char> end_of_input;
std::map<char,int> data;
while (it != end_of_input ) data[*(it++)]++;
for (const auto& e : data) std::cout << e.first << " " << e.second << "\n";
}
This is probably a lot at once, so lets go one by one.
std::istream_iterator<char> lets you extract characters from a stream as if you are iterating a container. So the while iteratates std::cin until it reaches the end of the input. Then *(it++) increments the iterator and returns the character extracted from the stream. data[x]++ accesses the value in the map for the key x and increments its value. If there is no value in the map yet for the key, it gets default initialized to 0.
For input: 11223 it prints
1 2
2 2
3 1
Your code has some issues, not sure if I can catch them all...
You are using VLA (variable lenght arrays) here: int a[n];. This is a compiler extension and not standard c++.
You access the array out of bounds. When i == 0 then j goes up to j<n-i-1 == n-1 and then you access a[j+1] == a[n], but the last valid index into the array is n-1. Same problem in the other loop (a[m+1]).
Assuming your sorting works, the last loop almost gives you the number of elements, but not quite, to fix it you can change it to...
int current = a[0];
int counter = 1;
for(int m=1;m<n;m++) {
if(a[m] == current) {
counter++;
} else {
std::cout << current << " appears " << counter << " times" << endl;
counter=1; // note: minimum freq is 1 not 0
current = a[m];
}
}

Run-Time Check Failure #2 - Stack around the variable 'numberchoices' was corrupted

I am having this terminal error every time I finish the debug program.
What I am doing:
[this program is a simple Lottery Numbers Comparison between user input numbers with the non-repeated random lottery numbers. e.g. using what if it got 4 right of 6]
but it turns out that the program is not working or at least, be stable.
Here's my code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <time.h>
#include <ctime>
#include <algorithm>
using namespace std;
int main()
{
cout << "[La Loteria Electronica]\n";
cout << "Escoge 6 n" << char(163) << "meros del (1 al 49): \n";
int numberchoices[] = { 0 };
for (int w = 1; w < 7; w++)
{
cout << "N" << char(163) << "mero #" << w << ": ";
cin >> numberchoices[w];
} // user numbers
//lottery numbers
int i, j, k, nums[51];
srand((int)time(0));
for (i = 1; i < 50; i++) nums[i] = i;
for (i = 1; i < 50; i++)
{
j = (rand() % 49) + 1;
k = nums[i]; nums[i] = nums[j]; nums[j] = k;
}
cout << "The lottery numbers are: ";
for (i = 1; i < 7; i++) cout << nums[i] << " ";
if (numberchoices[i] = nums[i])
{
cout << "gud\n";
}
if (numberchoices == nums)
{
cout << "gud 2";
}
/**/
cout << "\n\n";
system("pause");
Please ?
int numberchoices[] = { 0 };
for (int w = 1; w < 7; w++)
{
cout << "N" << char(163) << "mero #" << w << ": ";
cin >> numberchoices[w];
} // user numbers
You're declaring an array of size 1 and then you use it up to position 6 ?
I am having this terminal error every time I finish the debug program.
I'm surprised that you're not having a terminal error every time you start debug.
The access of numberchoises at positions from 1 to 6 are UB (Undefined Behavior). That is: all can happens.
Solution: try with
int numberchoices[7] = { }; // initialize all elements to zero!
Another point
if (numberchoices == nums)
not sure that you get what do you expect.
Do you want compare the integer pointer corresponding to numberchoices (a int[1], suggested int[7]) with the one corresponding to nums (a int[51]) ?