C++ // Trying to rewrite a working code to include my function - c++

My code is supposed to print an "a" amount of numbers (1 < a < n < 100000) which are simultaneously divisible by "x" and indivisible by "y" - all this for "t" amount of data sets.
I've written a code which does just that using only the main() function, but - as I'm learning about functions - I'm trying to rewrite this code to include my own function. For example, if I enter t=1, n=35, x=5 and y = 14, the output should be: "5 10 15 20 25 30".
Code 1 is the code which works fine, only with the main function. Code 2 is the code I'm currently working on which is supposed to include my function "check"
I've managed to rewrite the code 2 to a point where it returns the ASCII symbols corresponding to the numbers I'm supposed to obtain, but I'm having problems converting these symbols into numbers fulfilling my requirements.
When entering "1 7 2 4" as input data, the code returns two symbols instead of "2 6".
Any help with fixing this issue would be very appreciated...
Code 1:
#include <iostream>
using namespace std;
int main()
{
int t, n, x, y;
cin >> t;
for (int i=0; i<t; i++)
{
cin >> n >> x >> y;
for (int a=0; a<n; a++)
{
if ((a%x==0)&&(a%y>0))
cout << a << " ";
}
cout << endl;
}
return 0;
}
Code 2:
#include <iostream>
using namespace std;
string check (int n, int x, int y)
{
string result;
for (int a=0; a<n; a++)
{
if ((a%x==0)&&(a%y>0))
{
result += a;
result += " ";
}
}
return result;
}
int main()
{
int t, n, x, y;
cin >> t;
for (int i=0; i<t; i++)
{
cin >> n >> x >> y;
cout << check (n, x, y) << endl;
}
return 0;
}

What's the problem ?
This is because the following statement is understood by the compiler as if you wanted to add a single char to the string (so the char corresponding to the ascii code of a, if the string encoding is ascii):
result += a;
You may test this behavior of operator+= by trying:
result += 64; // ascii code for #
How to solve it ?
To get the result you expect, you need to convert a explicitly into a string. So change the line to:
result += to_string(a);
Isn't there an easier way ?
Alternatively, if you have a lot of formatting, and if you're comfortable with streams, you may want to consider stringstream:
string check (int n, int x, int y)
{
stringstream result;
for (int a=0; a<n; a++)
{
if ((a%x==0)&&(a%y>0))
{
result << a << " ";
}
}
return result.str();
}
The stringstreams behave as ordinary streams (e.g. cout), except that they write the result into memory. You can then easily transform the end result using the str() member function.

Related

Is integer overflow that evil?

Consider the following code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<int> a(n);
int sum = 0;
for (auto &it : a) {
cin >> it;
sum += it;
}
cout << sum << "\n";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
Input like (or anything greater than INT_MAX into k)
5 1234567891564
1 2 3 4 5
makes the program print
0
0 0 0 0 0
What actually happens? We don't use the value of k at all.
There is actually no integer overflow in your code. Well in a wider sense it there is, but in a more narrow sense integer overflow would happen for example with:
int k = 1234567891564;
What actually happens is that in this line
cin >> n >> k;
operator>> tries to read a int but fails. 1234567891564 is never actually assigned to k. When reading the input fails 0 will be assigned. Hence k comes out as 0.
Once the stream is in an error state, all subsequent calls to operator>> will silently fail as well. You should always check the state of the stream after taking input. For example:
if (std::cin >> n) {
// input succeeded use the value
} else {
// input did not succeed.
std::cin.clear(); // reset all error flags
}

Detecting the first digit in the second digits?

Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet.
Input: 1 4325121
Output: 2
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.
No arrays to be used here, only while loops and else-if conditions with basic coding knowledge and without the use of advanced coding.
As you said, you need to keep it as simple as possible. Then this can be a solution:
#include <iostream>
int main()
{
int first { };
int second { };
std::cin >> first >> second;
int quo { second };
int rem { };
int count { };
while ( quo > 0 )
{
rem = quo % 10;
quo /= 10;
if ( first == rem )
{
++count;
}
}
std::cout << "Result: " << count << '\n';
}
Using while loop
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 4325121;
int count = 0;
while(b > 0)
{
int m = b % 10;
if(m == a)
{
count++;
}
b /= 10;
}
cout << count;
return 0;
}
Nice little problem. But actually, to keep it as simple as possible no calculations are needed at all. I simplified my example, and it just keeps working on the input text, which is 100% sufficient to solve the problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
char digit;
std::string number;
cout << "Input: ";
cin >> digit >> number;
int count = 0;
for (char const character : number)
if (character == digit)
count++;
cout << "Result: " << count << endl;
return 0;
}
Given the question, this code solves the problem.

write a complete program that will read 3 NUMBers from user and calculates and displays the product only of the positive integers

This is what I've tried so far
// Calculate the product of three integers
#include <iostream> // allows program to perform input and output
using namespace std;
// function main begins program execution
int main()
{
int x; // first integer to multiply
int y; // second integer to multiply
int z; // third integer to multiply
int result; // the product of the three integers
cout << "Enter three integers: "; // prompt user for data
cin >> x >> y >> z;
result = x * y * z;
}
what can i do to solve this question?
EDIT:
If you do not need it to loop use a if instead of a while.
Looks like you need to study some conditional statements try:
result = x*y*z;
while(result < 0){
cout << "Enter three integers: "; // prompt user for data
cin >> x >> y >> z;
}
cout << result << endl;
Should work fine...
I would suggest using a condition to check the number at the input itself:
#include <iostream>
int main() {
int inum1 = 0;
std::cin >> inum1;
if (inum1 < 0) { inum1 = 1; }
int inum2 = 0;
std::cin >> inum2;
if (inum2 < 0) { inum2 = 1; }
int inum3 = 0;
std::cin >> inum3;
if (inum3 < 0) { inum3 = 1; }
std::cout << inum1*inum2*inum3 << "\n";
return 0;
}
Notice that in my example I have used std::cout and std::cin instead of using namespace std
use of using namespace std is fine if you're a beginner or the program is small, but is discouraged for large programs :)
If you find typing std:: tedious, you can instead include the following statements:
using std::cin;
using std::cout;
Also, printf and scanf is usually preferred over cin and cout for fast I/O.

Program does not work (leading zeroes)

You have to write an ITERATIVE procedure write_digit(d,x) that receives a digit d and a natural number x, and writes x times the digit d in the standard output (cout). For example, the call write_digit(3,5) writes 33333, whereas the call write_digit(5,3) writes 555.
I have problem with this code and it has to do with leading zeroes. Example:
write_digit(0,3) -> 000 -> My output: 0 (not a surprise)
The problem would be resolved in 1 minute if I was allowed to use iomanip
if (d == 0) cout << setw(x) << setfill('0') << "";
However, I CAN ONLY USE iostream and string.
#include <iostream>
using namespace std;
void write_digit(int d,int x) {
int original_d = d;
for (int i = 1; i < x; ++i) d = d*10 + original_d;
if (x == 0) cout << "";
else cout << d;
}
int main () {
int d,x;
cin >> d >> x;
write_digit(d,x);
}
You are completely overcomplicating the assignment, just make a simple loop without any edge conditions, it will work for any number, even for non-digits.
void write_digit(int d, int x) {
for (int i = 0; i < x; ++i) // Loop x times
std::cout << d; // Output digit
std::cout << '\n'; // Output newline
}

C++ Segmentation Fault with no pointers (HackerRank)

I solved a problem in Hacker Rank.
Input Format. The first line of the input contains an integer N.The next line contains N space separated integers.The third line contains a single integer x,denoting the position of an element that should be removed from the vector.The fourth line contains two integers a and b denoting the range that should be erased from the vector inclusive of a and exclusive of b.
Output Format. Print the size of the vector in the first line and the elements of the vector after the two erase operations in the second line separated by space.
CODE:
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
int n = 0, x = 0, value = 0;
vector<int> vk, vm;
vk.reserve(100000);
string k, m;
cin >> n;
cin.ignore();
getline(cin, k);
cin >> x;
cin.ignore();
getline(cin, m);
stringstream sk(k);
while (sk >> value)
vk.push_back(value);
stringstream sm(m);
while (sm >> value)
vm.push_back(value);
vk.erase(vk.begin() + x-1);
vk.erase(vk.begin() + vm[0]-1, vk.begin() + vm[1]-1);
cout << vk.size() << endl;
for (int i = 0; i < vk.size(); i++)
cout << vk[i] << " ";
cout << endl;
return 0;
}
But with this test case produce a "Segmentation Fault":
6
1 4 6 2 8 9
2
2 4
Can you help me to review my code and provide some feedback on what is the problem?
EDIT
Thanks to #john for the answer. Here is how it looks without the seg fault:
#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main() {
int n = 0, x = 0, y = 0, z = 0, value = 0;
vector<int> vk;
vk.reserve(100000);
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> value;
vk.push_back(value);
}
cin >> x >> y >> z;
vk.erase(vk.begin() + x-1);
vk.erase(vk.begin() + y-1, vk.begin() + z-1);
cout << vk.size() << endl;
for (int i = 0; i < vk.size(); i++)
cout << vk[i] << " ";
cout << endl;
return 0;
}
You're trying too hard with the your input code. It isn't correct because you seem to be assuming that cin.ignore() will skip the rest of the line, when it only skips the next character (which could be a space). I would guess this is the reason for the seg fault. You can tell how many numbers you have to read after you've read the first one. There is no need to use getline or stringsteam at all.
You don't need the vm vector. It will always contain two values, so just declare two variables. You could also pick much better names for all your variables.
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> value;
vk.push_back(value);
}
cin >> x >> vm0 >> vm1;