Appending vectors. Result won't print - c++

I'm trying to enter integers for a and b and then print those integers put together. For example, entering 1 2 3 4 for a and 4 3 2 1 for b would yield: 1 2 3 4 4 3 2 1. I don't understand why my program isn't printing this. Whenever I enter -1, nothing happens. Am I doing the process wrong while the program is running? Help is appreciated.
#include <iostream>
#include <vector>
using namespace std;
vector<int> append(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> c(n + m);
int i;
for (i = 0; i < n; i++)
c[i] = a[i];
for (i = 0; i < m; i++)
c[n + i] = b[i];
return c;
}
main()
{
vector<int>a, b, c;
int temp;
cin >> temp;
while (temp != -1) {
a.push_back(temp);
cin >> temp;
}
cin >> temp;
while (!cin.eof()) {
b.push_back(temp);
cin >> temp;
}
c = append(a, b);
for (int i = 0; i < c.size(); i++)
cout << c[i] << " ";
cout << endl;
}

You have two loops, one to input the vector a and another to input b.
Hitting -1 once would terminate only the first loop. The second one is terminated by an eof which you still haven't entered. So either enter an eof (specific to your system) or have the second loop terminate at -1 (in which case you'll need to enter -1 once more).

You say
Whenever I enter -1, nothing happens.
That's because you reach the second cin >> temp statement at that time (just before while.eof() loop). That's when you start inputting values for b vector. You end that loop by entering EOF character in the stream (CTRL+Z on windows, CTRL+D on linux).

Related

Find Extreme Value in Integers Given

I'm trying to find the highest value in a given list, but in an input list like this
7 385 -390 305 470 -145 255 30
my output is wrong, 385 instead of 470.
Could anyone please guide me towards my error!
Task description:
Read in an input value for variable numIn. Then, read numIn integers from input and output the largest of the integers read. End with a newline.
Ex: If the input is 2 345 -5, then the output is:
345
my code below
#include <iostream>
using namespace std;
int main() {
int numIn;
int high = 0;
cin >> numIn;
for (int i = 0; i < numIn; i++) {
cin >> numIn;
if (numIn > high) {
high = numIn;
}
}
cout << high << endl;
return 0;
}
First of all, your list has negative numbers. You can't set the default value of high to 0 since a list with all negative numbers won't work if you do this.
The error in your loop occurs because you overwrite numIn. Use a different variable for the number of input numbers.
cin >> numIn; // numIn is the number of input numbers
for (int i = 0; i < numIn; i++) {
cin >> numIn; // oops, numIn is now the first input number. it has been overwritten.
if (numIn > high) {
high = numIn;
}
}
A correct solution would look like this:
#include <iostream>
int main() {
int N; // assume that N >= 1. You could also replace this with numIn.
std::cin >> N;
int max;
std::cin >> max; // take in the first integer outside the loop
for (auto i = 1; i < N; i++) { // loop which runs N - 1 times
int E;
std::cin >> E;
max = std::max(max, E);
}
std::cout << max << '\n';
}
Without using std::max()
If you don't want to use std::max(), replace the line where you use it with a normal comparison (this is what std::max() does internally too)
if (E > max) { max = E; }

Get all input of int from cin separated with space in c++

N = Input How much attempt (First Line).
s = Input How much value can be added (Second, fourth and sixth lines).
P = Input of numbers separated with space.
Example :
3 ( Input N )
2 ( s 1 )
2 3
3 ( s 2 )
1 2 3
1 ( s 3 )
12
Example :
Read #1: 5 (Output s1 = 2 + 3)
Read #2: 6 (Output s2 = 1+2+3)
Read #3: 12 (Output s3 = 12)
I've been searching and trying for very long but couldn't figure out such basic as how to cin based on given numbers, with spaces and add all values into a variable. For example:
#include <iostream>
using namespace std;
int main() {
int l, o[l], r, p[r], i;
cin >> l;
for(i = 0; i < l; i++) {
cin>>o[l];
r = o[l]; // for every o[0] to o[l]
}
while (cin>>o[l]) {
for (i = 0; i < l; i++){
cin>>p[o]; // for every o[0] to o[l]
// i.e o[l] = 1 then 2 values can be added (because it starts from zero)
// input 1 2
// o[1] = {1, 2}
int example += o[1];
cout<< "Read#2: " << example;
}
}
}
And it doesn't work. Then i found getline(), ignoring the s and just input anything that will finally be added to a number, turned out it is only usable for char string. I tried scanf, but I'm not sure how it works. So im wondering if it's all about s(values) × 1(column) matrix from a looping but sill not sure how to make it. Any easy solutions to this without additional libraries or something like that? Thanks in advance.
#include <iostream>
using namespace std;
int main() {
int t; //number of attempts
cin >> t;
while(t--) { // for t attempts
int n, s = 0; //number of values and initial sum
cin >> n;
while (n--) { //for n values
int k; //value to be added
cin >> k;
s += k; //add k to sum
}
cout << s << "\n"; //print the sum and a newline
}
return 0;
}
If you want to add more details, (i.e. print Read#n on the nth attempt), you can always use
for (int i = 1; i <= n; i++)
to replace while(t--) and at the end of the attempt just print
cout << "Read#" << i << ": " << s << "\n";

Unıque Random Number Check form Array c++

#include <iostream>
#include<ctime>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
int arr[10];
int a = pow(10, num);
int b = pow(10, (num - 1));
srand(static_cast<int>(time(NULL)));
do {
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
for (int m = 0; m < num; m++)
{
for (int j = 0; j < m; j++) {
if (m != j) {
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
cout << num2 << endl;
} while (!cont);
return 0;
}
I want to take a number from the user and produce such a random number.
For example, if the user entered 8, an 8-digit random number.This number must be unique, so each number must be different from each other,for example:
user enter 5
random number=11225(invalid so take new number)
random number =12345(valid so output)
To do this, I divided the number into its digits and threw it into the array and checked whether it was unique. The Program takes random numbers from the user and throws them into the array.It's all right until this part.But my function to check if this number is unique using the for loop does not work.
Because you need your digits to be unique, it's easier to guarantee the uniqueness up front and then mix it around. The problem-solving principle at play here is to start where you are the most constrained. For you, it's repeating digits, so we ensure that will never happen. It's a lot easier than verifying if we did or not.
This code example will print the unique number to the screen. If you need to actually store it in an int, then there's extra work to be done.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
int main() {
std::vector<int> digits(10);
std::iota(digits.begin(), digits.end(), 0);
std::shuffle(digits.begin(), digits.end(), std::mt19937(std::random_device{}()));
int x;
std::cout << "Number: ";
std::cin >> x;
for (auto it = digits.begin(); it != digits.begin() + x; ++it) {
std::cout << *it;
}
std::cout << '\n';
}
A few sample runs:
Number: 7
6253079
Number: 3
893
Number: 6
170352
The vector digits holds the digits 0-9, each only appearing once. I then shuffle them around. And based on the number that's input by the user, I then print the first x single digits.
The one downside to this code is that it's possible for 0 to be the first digit, and that may or may not fit in with your rules. If it doesn't, you'd be restricted to a 9-digit number, and the starting value in std::iota would be 1.
First I'm going to recommend you make better choices in naming your variables. You do this:
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
What are num and num2? Give them better names. Why are you cin >> str? I can't even see how you're using it later. But I presume that num is the number of digits you want.
It's also not at all clear what you're using a and b for. Now, I presume this next bit of code is an attempt to create a number. If you're going to blindly try and then when done, see if it's okay, why are you making this so complicated. Instead of this:
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
You can do this:
for(int index = 0; index < numberOfDesiredDigits; ++index) {
arr[index] = rand() % 10;
}
I'm not sure why you went for so much more complicated.
I think this is your code where you validate:
// So you iterate the entire array
for (int m = 0; m < num; m++)
{
// And then you check all the values less than the current spot.
for (int j = 0; j < m; j++) {
// This if not needed as j is always less than m.
if (m != j) {
// This if-else is flawed
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
You're trying to make sure you have no duplicates. You're setting cont == true if the first and second digit are different, and you're breaking as soon as you find a dup. I think you need to rethink that.
bool areAllUnique = true;
for (int m = 1; allAreUnique && m < num; m++) {
for (int j = 0; allAreUnique && j < m; ++j) {
allAreUnique = arr[m] != arr[j];
}
}
As soon as we encounter a duplicate, allAreUnique becomes false and we break out of both for-loops.
Then you can check it.
Note that I also start the first loop at 1 instead of 0. There's no reason to start the outer loop at 0, because then the inner loop becomes a no-op.
A better way is to keep a set of valid digits -- initialized with 1 to 10. Then grab a random number within the size of the set and grabbing the n'th digit from the set and remove it from the set. You'll get a valid result the first time.

Why isn't the value of a variable that is serving as "count " not resetting to zero when the loops reiterates?

This is the code that I have written and I am giving you sample inputs and outputs to this just to clear my question even more
Sample input
2 (value of t, which are test cases)
3 (number of inputs )
2 4 2
3
0
2
3
I am getting output as
1
1
I should be getting output as
1
0
#include<iostream>
#include<vector>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
vector<ll int> x;
ll int n;
cin >> n;
ll int i, ent;
for (i = 0; i < n; i++)
{
cin >> ent;
x.push_back(ent);
}
vector<ll int>::iterator y,z;
for(y=(x.begin());y!=(x.end()-1);y++)
for (z = (x.begin() + 1); z != (x.end()); z++)
{
int count=0;
if (*y + *z == *y * (*z))
count++;
}
cout << count<<endl;
}
return 0;
}
Updated code: But still having the same problem
#include<iostream>
#include<vector>
#define ll long long
int main()
{
int t;
std ::cin >> t;
while (t--)
{
std :: vector<ll int> x;
ll int n;
std :: cin >> n;
ll int i, ent;
for (i = 0; i < n; i++)
{
std :: cin >> ent;
x.push_back(ent);
}
std::vector<ll int>::iterator y,z;
int count = 0;
for(y=(x.begin());y!=(x.end()-1);y++)
for (z = (x.begin()+1); z != (x.end()); z++)
{
if (*y + *z == *y * (*z))
count++;
}
std ::cout << count<< std ::endl;
}
return 0;
}
Your first problem is that you're accessing the variable count outside its scope. It is declared in the scope of the inner for() loop, and you're trying to print it outside of it. Move its declaration above the for() loops
Now, to answer your question. In the second iteration of the while() loop (vector 0, 2, 3),
in one of the for() loops' iterations, *x and *z will be equal to 2. What you should have done to avoid it is to initialize z as z = y + 1
Your code as written should produce that output (if it even complies...) g++ won't compile it because you reference count after the loop it was created in. count is scoped to that loop so it doesn't exist outside. Anyway I assume you're using some compiler switches or a compiler that allows that.
You effectively make one list of numbers and loop through it checking the mathematical relation you coded (ie when two numbers added together is the same as them multiplied together.) Your first loop goes from the first value to the second last value (because you check for equality against end() - 1) I'm not sure if that's what you really wanted or not. Your second loop starts at the second value and then goes till the last value. So in your second test case your second number is 2 and 2 will be used for the parameter *y and then it is the first value in the second loop so you're doing the check with 2 and 2 and 2+2 == 4 == 2*2 so the check passes and count is incremented. Try the code below to get some insight into what you're doing (note that I removed the declaration of count from inside the loop and moved it just above the declaration of y and z which was required for me to compile it with my system):
{
cout << "y:" << *y <<" z:" << *z << endl;
if (*y + *z == *y * (*z)){
cout << "match " << *y << " " << *z << endl;
count++;
}
}
Name conflict between std::count and your local count. Remove using namespace std; and you will have more meaningful error message: as unknown identifier count, as count should be declared outside of the loop:
int count=0;
for(y=(x.begin());y!=(x.end()-1);y++)
for (z = (x.begin() + 1); z != (x.end()); z++)
{
if (*y + *z == *y * (*z))
count++;
}
std::cout << count << std::endl;
Note: std::cout << function_name outputs 1 with implicit bool conversion.
Note: logic of the code itself might still have issues

Error in inputting a 2d character array

I am entering a 2D character array and have to stop entering when the user hit the enter key . But my code is not showing any output.
Input:
5 // where this is the number of columns,
// number of rows are unknown so have taken maximum rows as: 40
array:
toioynnkpheleaigshareconhtomesnlewx
Expected output:
i = 7, j = 5
Here is my code:
int main(){
char a[100][100];
int n, i, j, p, q;
cin >> n;
if(n==0)
exit(0);
for(i = 0; i < 40; i++){
for(j = 0; j < n; j++){
cin >> a[i][j];
if(a[i][j]==13) // 13 = ASCII code for enter key
goto jump;
}
}
jump:
cout<<i<<"\n"<<j<<"\n";
}
But it is not printing anything.
What could be wrong with it?
This is happening because cin ignores white space and newline ('\n', whose ASCII code is 13). This means the condition if(a[i][j] == 13) never evaluates to true.
Solution: Use cin.get(a[i][j]) instead of cin>>a[i][j]
This works because the cin.get() method does not ignore the newline character ('\n').