We often need to enter a bunch of numbers, and the number of data is unknown. At this time it is not possible to use the number of data as input whether the end of the judging standard.
In this case, we can enter data in the following two ways.
Method One: Determine the return (with getchar () = = ' \ n ' can be judged)
1 //take integers as an example2#include <iostream>3#include <vector>4#include <algorithm>5 using namespacestd;6 7 intMain () {8vector<int>v;9 inttmp;Ten while(cin>>tmp) { One V.push_back (TMP); if(getchar () = = '\ n')break; - } the //Output - for(intval:v) { -cout<<val<<Endl; - } + return 0; -}
1 //take a string as an example2#include <iostream>3#include <vector>4#include <algorithm>5 using namespacestd;6 7 intMain () {8vector<string>v;9 stringtmp;Ten while(cin>>tmp) { One V.push_back (TMP); if(getchar () = = '\ n')break; - } the //Output - for(stringval:v) { -cout<<val<<Endl; - } + return 0; -}
Method two: processing with Istringstream Stream object
1 //take a string as an example2#include <iostream>3#include <sstream>//Istringstream4#include <string>5 using namespacestd;6 intMain ()7 {8 //string str= "I like wahaha! miaomiao~";9 stringstr;TenCin>>str; Istringstream is (str); A strings; - while( is>>s) - { thecout<<s<<Endl; - } -}
1 //take an integer as an example (the number of rows as a string input before conversion)2#include <iostream>3#include <sstream>//Istringstream4#include <string>5 using namespacestd;6 intMain ()7 {8 //string str= "0 1 2 4 5";9 stringstr;Ten getline (CIN,STR); Istringstream is (str); A intS//this translates to the int type. - while( is>>s) - { thecout<<s+1<<endl;//now it's ready to operate. - } -}
Input method in the case of unknown number of C + + data