在這里輸入影像描述 我使用了代碼( if (!(cin >> arr[i])) )來檢查來自用戶的輸入是否與 int 型別(如字串、字符)不同以停止讀入陣列(arr1),并且然后我不能將它與第二個陣列 (arr2) 一起使用兩次,它沒有讀取輸入并直接轉到 cin.clear 并回傳...你能幫我嗎?非常感謝它^^ 在此處輸入圖片說明
uj5u.com熱心網友回復:
看來你的意思是以下
#include <limits>
//...
if ( not ( std::cin >> arr[i] ) )
{
//...
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
uj5u.com熱心網友回復:
以下是兩種方式的完整作業示例。給定的程式讀取與用戶在控制臺上輸入一樣多的整數。例如,用戶可以輸入 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 可以在這里檢查。
重要的提示
The advantage of using std::vector
over built in array(in this case) is that you don't have know the size of the vector beforehand. That is std::vector
's size is not fixed as opposed to built in arrays. So it is preferable because you don't know how many input the user is going to enter. std::vector
can handle this accordingly and add only valid(integer type) input. But when using built in arrays you must know/specify the size of the array beforehand. This in turn means you must know beforehand how many integers the user is going to enter, which is not practical.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/328485.html
上一篇:使用模數找出2次之間的差異?