Method for entering multiple sets of data in C and C++

  • 2020-05-27 06:36:49
  • OfStack

If at the beginning of learning algorithm, do algorithm problem, the problem will often require the input of a number of groups of data, for the beginning of learning small white, may not know how to calculate the input of a number of groups of data, also do not know how to deal with, just remember, the method record 1

How to input multiple sets of data?

If you want to input more than one set of data, you need to read a variable amount of input data. In this case, you need to read more and more data until there is no new input.

Method 1:


#include <stdio.h> 
int main() 
{ 
  int a; 
  while(scanf("%d",&a)!=EOF) 
  { 
    printf("%d\n",a); 
  } 
  return 0; 
} 

Above is the method using C language, taking the input statement as the judgment condition of while loop. When the input data is not the end of the file (EOF), continuous input can be realized

Method 2:


#include <iostream> 
using namespace std; 
int main() 
{ 
  for(int i;cin>>i;) 
  { 
    cout << i << endl; 
  } 
  return 0; 
} 

Method is to use C + + 2 for cycle, the input statement as for condition part of the loop, and the omission don't write expression part, some can change the value of i because of the condition, so the cycle without expression part, among them, the condition part constantly check the content of the input stream, as long as you read through all the input met a typo or terminate the loop

Method 3:


#include <iostream> 
using namespace std; 
int main() 
{ 
  int a; 
  while(cin>>a) 
  { 
    cout << a << endl; 
  } 
  return 0; 
} 

Method 3 is similar to method 2 in that it USES the istream object as a loop judgment condition to detect the state of the flow. If the flow is valid, that is, the flow does not encounter an error, then the detection is successful. The state of the istream object becomes invalid when a file terminator (EOF) is encountered or when an invalid input is encountered. An istream object in an invalid state will make the condition false.


Related articles: