C++输入数据流用回车符判断终止

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leolewin/article/details/51064808

实际问题:很多读入数据都希望用回车来结束,比如输入一串double(输入时用空格隔开),存入到一个vector或数组中,最后用回车结束(关键是个数不限,所以不能用固定循环次数来限定它。 
         咋一看很简单,要编程突然还没头脑~~~关键是字符和整数或浮点数据的区别。 
        用cin.get()来获取流中的字符,然后判读是否为回车符,如果不是则将字符放回流中(unget),

#include "stdafx.h" 
#include 
using namespace std;

int _tmain(int argc, _TCHAR* argv[]) 

    char c; 
    double d; 
    while((c=cin.get())!='\n') 
    { 
        cin.unget(); 
        cin>>d; 
    } 
    cout<
    while((c=cin.get())!='\n') 
    { 
        cin.unget(); 
        cin>>d; 

cin.get(); //此函数作用为消除数据后的回车

    } 
    cout<
    cin>>d; 
    return 0; 
}

猜你喜欢

转载自blog.csdn.net/leolewin/article/details/51064808