C++实现给多个变量传值

来源:互联网 发布:算法导论英文版 百度云 编辑:程序博客网 时间:2024/06/06 04:35
cout << "input your arry " << endl;    int a,b;    vector<int> num;    while (cin >> a)        num.push_back(a);    cin.clear();//这里使用这两句后,可以往下面的b里读入数据    cin.sync();    cout << "input your target" << endl;    cin >> b;    cin.clear();//这里继续使用后,如果后面的函数还有自己的输出就可以顺利输出了。    cin.sync();

cin.clear()是用来更改cin的状态标示符的。
cin.sync()是用来清除缓存区的数据流的。
如果标示符没有改变那么即使清除了数据流也无法输入。所以两个要联合起来使用。
例如
定义整型变量,然后输入的是char型,就会报错

#include <iostream> using namespace std; int main()  {             int a;             while(1)             {                         cin>>a;                         if(cin.fail())  //  如果输入char型,failbit就为1                     {                                     cout<<"输入有错!请重新输入"<<endl;                                     cin.clear();       //将failbit置为0                               cin.sync();   //清空流                         }                         else                         {                                     cout<<a;                                     break;                         }             }             system("pause"); }

还看了关于cin.ignore()的讲解
ignore(int a,char ch)
a:在一行中可以忽略的字符的最大数目,也就是说,a个字符都不会被读入
ch:是字符表达式,遇到这个字符后,就不再忽略,而是读入接下来的值。如果没有到a个,但是遇到该字符也要停止ignore
这一段详解见博客:
http://blog.csdn.net/imkelt/article/details/52202002

#include<iostream>#include<cstdlib>int main(){  int ival1 = 0, ival2 = 0;  std::cin >> ival1;  std::cin.ignore(100, '\n');  std::cin >> ival2;  std::cout << "ival1 = " << ival1 << std::endl;  std::cout << "ival2 = " << ival2 << std::endl;  system("pause");  return 0;}

输入:
12 24 34 56
23 56 78 90
输出:
ival1 = 12
ival2 = 23

②把 std::cin.ignore(100, ‘\n’);改为
std::cin.ignore(2, ‘\n’);
输入:
23 45 67

输出:
ival1 = 23
ival2 = 5
忽略两个字符:一个空格,一个4
因为我们所用的IO对象cin cout 都是操纵char数据的,不管我们输入的是什么数据,cin cout 都会转成 char来处理,例如我们想要输出的是一个整形变量的值,那么在输出前,cout会将该变量的值转成字符,在进行输出(C++ Primer Plus中有一句话:In essence, the C++insertion operator adjusts its behavior to fit the type of data that follows it.),所以上面ignore清除掉了一个空格和一个字符5,所以缓冲区中剩余5、67,所以ival2等于5。

③如果cin.ignore()不给参数,则默认参数为cin.ignore(1,EOF),即把EOF前的1个字符清掉
EOF为ctr+z
输入:12 34 56
ival1=12
ival2=34
清掉了56

阅读全文
0 0
原创粉丝点击