[英]C++ How to read more integers in one line in a function?
我當前有一個函數讀取一個整數,並檢查錯誤(太大太小或不是整數。
int be_egesz(string question, int minval, int maxval, string error_message)
{
bool error;
string tmp;
int number;
do
{
cout << question << endl;
cin >> szam;
error=cin.fail() || cin.peek()!='\n' || (number<minval || number>maxval);
if (error)
{
cout << error_message << endl;
}
cin.clear();
getline(cin,tmp,'\n');
}while(error);
return number;
}
如何轉換此函數,以便它可以在一行中讀取多於1個整數?
示例輸入:1 2
或者,如何在一行中使用此功能2次
怎么樣的std::cin
和讀取兩個變量?
#include <iostream>
using std::cout;
using std::cin;
int main() {
int x;
int y;
cin>>x>>y;
cout<<"Value 1: "<<x<<"\n"<<"Value 2: "<<y<<"\n";
return 0;
}
輸入:
1 5
輸出:
Value 1: 1
Value 2: 5
您還可以使用2個以上的整數值:
int x;
int y;
int z;
cin>>x>>y>>z;
如果它們太大或太小就比較它們就像任何其他場景一樣:
cin>>x>>y;
if(x > 10)
cout<<x<<" is Greater than 10\n";
if(y > 10)
cout<<y<<" is Greater than 10\n";
這里要說的重要的是我認為>>
運算符默認從流(你的情況下是stdin)中提取所有字符直到下一個空格。 因此,如果在標准輸入中編寫1 2
,則需要兩次調用>>
運算符來讀取1和2.但它們不需要在代碼中位於同一行。
如果您需要一次檢查一個號碼,您可以再次調用您的功能。 舉個例子:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
int x;
string str;
getline(std::cin, str);
stringstream ss(str);
while (! ss.eof()) {
ss >> x;
cout << "Num: " << x << endl;
}
return 0;
}
此代碼使用getline
讀取單行輸入並將其存儲在字符串str
。 然后它創建一個帶有該行副本的字符串,並在while
循環中一次提取一個數字(它在每個空格處停止字符提取),直到該流為空。 因此,在輸入中每個數字執行一次循環。
如果你輸入:
1 2 3 4
你得到:
Num: 1
Num: 2
Num: 3
Num: 4
因此,您可以在類似的代碼中插入函數並在循環內調用它。
我的主要問題是調查錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.