[英]how can i use (!(cin>>a)) twice times?
看來你的意思是以下
#include <limits>
//...
if ( not ( std::cin >> arr[i] ) )
{
//...
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
以下是兩種方式的完整工作示例。 給定的程序讀取與用戶在控制台上輸入一樣多的整數。 例如,用戶可以輸入 30 或 300 個輸入,其中一些可能是整數類型,而另一些可能是一些其他類型,如字符串。 數組/向量將根據需要僅在其內部添加整數類型輸入。
解決方案 1 :使用內置數組
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string line;
//in case of using array, size must be fixed and predetermined
int arr[4] = {0}; //all elements are initialzed to zero. Also you can choose array size according to your needs
int i = 0;//this variable will be used to add element into the array
int count = 0;
getline(std::cin, line);
std::istringstream s(line);
//take input(from s to i) and then checks stream's eof flag status
while(s >> i || !s.eof()) {
//check if either failbit or badbit is set
if(s.fail())
{
//clear the error state to allow further operations on s
s.clear();
std::string temp;
s >> temp;
continue;
}
else
{
arr[count] = i;
++count;
if(count>=4)
{
break;//break the loop so that you don't go beyond array size
}
}
}
//print out the elements of the array
for(int i: arr)
{
std::cout<<"elem: "<<i<<std::endl;
}
return 0;
}
解決方案 1 可以在這里檢查。
解決方案 2 :使用std::vector
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
int main()
{
std::string line;
std::vector<int> vec;
int i = 0;//this variable will be used to add element into the array
getline(std::cin, line);
std::istringstream s(line);
//take input(from s to i) and then checks stream's eof flag status
while(s >> i || !s.eof())
{
//check if either failbit or badbit is set
if(s.fail())
{
//clear the error state to allow further operations on s
s.clear();
std::string temp;
s >> temp;
continue;
}
else
{
vec.push_back(i);
}
}
//print out the elements of the array
for(int i: vec)
{
std::cout<<"elem: "<<i<<std::endl;
}
return 0;
}
解決方案 2 可以在這里檢查。
使用std::vector
優於內置數組(在這種情況下)的優點是您事先不知道向量的大小。 那是std::vector
的大小不是固定的,而不是內置數組。 所以最好是因為你不知道用戶將輸入多少輸入。 std::vector
可以相應地處理這個並只添加有效的(整數類型)輸入。 但是在使用內置數組時,您必須事先知道/指定數組的大小。 這反過來意味着您必須事先知道用戶將要輸入多少個整數,這是不切實際的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.