How to implement Java “Scanner” in C++?

You seem to be using Scanner to read one integer at a time from the standard input stream. This is easily accomplished with the extraction operator, operator>>.

Replace this code:

    Scanner scan = new Scanner(System.in);

    int number=0;
    int loopValue = scan.nextInt();
   //System.out.println("print: "+loopValue);

    for(int i=0;i<loopValue;i++)
    {
        number = scan.nextInt();
       // System.out.println("print: "+number);

With this:

    int number=0;
    int loopvalue=0;
    std::cin >> loopvalue;

    for(int i = 0; i < loopValue; i++)
    {
        std::cin >> number;

You should check the value of std::cin after the >> operations to ensure that they succeeded.

Refs:

Leave a Comment