Home > Blockchain >  Get all input of int from cin separated with space in c
Get all input of int from cin separated with space in c

Time:10-09

N = Input How much attempt; (First Line).
s = Input How much value can be added; (Second, fourth and sixth).
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 long 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 sure it doesn't work, and never will. 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, not sure how it works. So im wondering if it's all about s(values) x 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.

CodePudding user response:

#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";
  •  Tags:  
  • c
  • Related