tianz
tianz

Reputation: 2193

Reading an unknown number of inputs

I need to read an unknown number of inputs using either C++ or Java. Inputs have exactly two numbers per line. I'd need to use cin or a System.in Scanner because input comes from the console, not from a file.

Example input:

1 2

3 4

7 8

100 200

121 10

I want to store the values in a vector. I have no idea how many pairs of numbers I have. How do I design a while loop to read the numbers so I can put them into a vector?

Upvotes: 3

Views: 17911

Answers (5)

Hrithik Raj
Hrithik Raj

Reputation: 23

For someone looking for less fancier C++ code:

    #include<iostream>
    #include<vector>
    int main(){
        std::vector<int>inputs;  //any container
        for(int i;std::cin>>i;)  //here the magic happens
            inputs.push_back(i); //press Ctrl+D to break the loop
        for(int num:inputs)      //optional 
            std::cout<<num<<endl;
    }

Upvotes: 0

Rao Virinchi
Rao Virinchi

Reputation: 329

Instead of using a buffered reader, one can use Scanner as follows to accomplish the same

import java.util.*;

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    while(true)
    {
        String Line = new String(scan.nextLine());
        if(Line.length()==0)
        {
            break;
        }
    }
}

}

Upvotes: 1

vaibhav taneja
vaibhav taneja

Reputation: 11

Only workaround I found :

import java.io.*;

class Solution {
    public static void main(String args[] ) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int i=1 ;
        String line =br.readLine();
        while(line.length()>0){
            System.out.println(line);
            line = br.readLine();
        }    
    }
}

Upvotes: 0

Qaz
Qaz

Reputation: 61970

You can use an idiomatic std::copy in C++: (see it work here with virtualized input strings)

std::vector<int> vec;
std::copy (
    std::istream_iterator<int>(std::cin), 
    std::istream_iterator<int>(), 
    std::back_inserter(vec)
);

That way, it will append onto the vector each time an integer is read from the input stream until it fails reading, whether from bad input or EOF.

Upvotes: 6

Osiris
Osiris

Reputation: 4185

Java:

Scanner sc = new Scanner(System.in);
String inputLine;
while(sc.hasNextLine()) {
  inputLine = sc.nextLine();
  //parse inputLine however you want, and add to your vector
}

Upvotes: 4

Related Questions