Input method in the case of unknown number of C + + data

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.