0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
vitrify
  • 21
  • 2
  • 2
    `cin >> a, b;` is a bug. The comma operator does not do what you think. – drescherjm Apr 05 '22 at 17:38
  • You may want to read line by line like option #2 of this answer: [https://stackoverflow.com/a/7868998/487892](https://stackoverflow.com/a/7868998/487892) and complain / exit if the format is not 2 integers in a line. – drescherjm Apr 05 '22 at 17:42
  • 1
    [Enabling your compiler's warnings](https://godbolt.org/z/fxhMaMe9G) will likely inform you of these bugs. – Drew Dormann Apr 05 '22 at 17:42

2 Answers2

3

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

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;
H.M
  • 425
  • 2
  • 16