Home > Net >  Program not taking expected Input, can't find out why
Program not taking expected Input, can't find out why

Time:04-06

This program should take input a,b equal to the value of t, instead it seems to only take one input and then deliver the output. For example, the inputs of:

3
1 2
100 200  
40 15  

leads only to an output of:

3
1 2
01  
100 200

the expected output should instead be:

1
100
10

The program:

#include <iostream>

using namespace std;

int main()
{
   int t;
   cin >> t;
   for(int i; i<t; i  ){
    int a, b;
    int x = a%b;
    cin >> a, b;
    cout << x;

   }
    return 0;
}

I have tried breaking up cin >> a, b; into two different commands but that didn't work. I also messed around with where the variables are located in the code. None of that helped.

CodePudding user response:

For starters using the initializer in the declaration

int x = a%b;

invokes undefined behavior because variables a and b were not initialized and have indeterminate values.

Also this statement

cin >> a, b;

is equivalent to the expression statement with the comma operator

( cin >> a ), b;

Instead you need to write

int a, b;

cin >> a >> b;

int x = a % b;

cout << x << '\n';

Also the variable i was not initialized in the for loop

for(int i; i<t; i  ){

You have to write

for ( int i = 0; i < t; i   ){

If you do not want to mix the input with the output when use the standard container std::vector<int> for example the following way

#include <iostream>
#include <vector>

int main()
{
    unsigned int t = 0;

    std::cin >> t;

    std::vector<int> v( t );

    for ( auto &x : v )
    {
        int a, b;

        std::cin >> a >> b;

        x = a % b;
    }

    for ( const auto &x : v )
    {
        std::cout << x << '\n';
    }

    return 0;
}

CodePudding user response:

common mistakes in using std::cout and std::cin ,is using comma instead of shift operator when seprate arguments passed to std::cin and std::cout.

so you should use ">>" of "," when pass new arguments:

std::cin >> a >> b;
  • Related