1
我正在創建一個程序來驗證通過命令行傳遞的電話號碼。用戶必須遵循以下標準(xxx)-xxx-xxxx。通過命令行傳遞帶圓括號的參數C++
每當我使用圓括號時,出現以下錯誤:「-bash:意外標記附近的語法錯誤。」
我的代碼應該沒有問題,但在這裏是incase。
#include <iostream>
#include <cctype>
#define die(errmsg) cerr << errmsg << endl; exit(1);
#define ISDIGIT(c) (c>=48 && c<=57);
using namespace std;
int main(int argc, char ** argv)
{
string phoneNumber = argv[1];
//Validations
if(phoneNumber.size() != 14)
{
die("Not the right amount of numbers and characters.
Use this format, (415)-713-9807.");
}
else if(phoneNumber[0] != '(' || phoneNumber[4] != ')')
{
die("Please use parenthesis around area code. Ex: (415).");
}
else if(phoneNumber[5] != '-' || phoneNumber[9] != '-')
{
die("Please use dashes to sepearte numbers like so, (415)-713-9807.");
}
//Check for numbers by splitting numbers in groups.
string left = phoneNumber.substr(1,3);
string middle = phoneNumber.substr(6,3);
string right = phoneNumber.substr(10);
string number = left + middle + right;
for(int i=0; i<number.size(); i++)
{
if(!isdigit(number[i]))
{
die("Please enter numbers only, such as (415)-713-9807.");
}
}
cout << "Valid Phone Number.";
}
'()'在bash中用來創建一個子shell。你需要將它們轉義爲'\('和'\)'來將它們作爲命令行參數傳遞。 –
謝謝,這工作。 – jfoose