1. 程式人生 > >記錄各個七七八八的輸入 持續更新中

記錄各個七七八八的輸入 持續更新中

校招線上筆試做程式設計題的時候,輸入的要求常常是不同的,記錄每一次的輸入,等以後線上筆試的時候就不慌了,噗哈哈

 

判斷數字合輯

 

1、每次輸入一個數字,當輸入的不是數字的時候,迴圈結束

(注:當輸入 回車空格tab鍵的時候,程式不會退出)

int main() {

	//資料輸入介面
	int input = 0;
	while (1) {
		//如果input不是數字,則跳出迴圈
		cin >> input;
		if (cin.fail()) {
			//not a number
			cout << "當前輸入非數字,程式退出" << endl;
			break;
		}
		//number]

	}

	return 0;
}

 

 

2、輸入一個string,判斷string中是否全都是數字,如果存在非數字,則要求使用者重新輸入

#include <cctype>
#include<string>
#include<iostream>
using namespace std;
int main(void)
{
    string str;
    bool shuzi;
    do
    {
           shuzi=true;
           cout<<"請輸入數字:"<<endl;
           cin>>str;
           
           for(string::iterator iter=str.begin();iter!=str.end();iter++)
           {
                  if(!isdigit(*iter))
                  {
                                     shuzi=false;
                                     cout<<"輸入含有非數字字元,請從新輸入。"<<endl;
                                     break;
                  }
                  
           }
           
    }while(!shuzi);
    system("pause");
    return 0;
    
}

 

 

3、通過ascii碼判斷輸入的char型別元素是否為數字

個位數的ascii碼為 48(數字 0 的ascii碼)到57(數字 9 的ascii碼)之間。

#include<string>
#include<iostream>
using namespace std;


int main(void)
{
	string str;
	bool shuzi;
	do
	{
		shuzi = true;
		cout << "請輸入數字:" << endl;
		cin >> str;

		for (string::iterator iter = str.begin(); iter != str.end(); iter++)
		{
			if (*iter < 48 || *iter > 57)
			{
				shuzi = false;
				cout << "輸入含有非數字字元,請從新輸入。" << endl;
				break;
			}

		}

	} while (!shuzi);
	system("pause");
	return 0;

}