2011-09-01 186 views
3

我的很多節目需要在命令行參數,一個例子如下:命令行參數

a.out [file-name] [col#] [seed] 

然後,如果我想使用的參數,我有很好的,易於使用功能如:

atof(argv[..]) and atoi(argv[..]) 

我想知道這樣的簡單/簡單函數是否存在C++。我想簡單地做到這一點:

cin >> col_num >> seed; 

但是,這並不工作...它等待輸入(不是命令行),然後將其輸出...

感謝

+6

如果您相信它們滿足您的需求,那麼可以從C++獲得'atof'和'atoi'。 –

+0

你爲什麼突然停止使用'argv'?我的意思是... *是*參數數組... –

+0

哦。我認爲那些是C函數(在C++中顯然是兼容的)。我只是想知道是否有更多的C++ ish方法 – Amit

回答

5

解決方案1:
可以代替使用lexical_castatoi

int x = boost::lexical_cast<int>("12345"); 

儘管在try-catch塊中使用boost::lexical_cast。投射無效時投擲boost::bad_lexical_cast

解決方案2:
如果你不使用升壓,需要一個標準的C++解決方案,您可以使用流。

std::string hello("123"); 
std::stringstream str(hello); 
int x; 
str >> x; 
if (!str) 
{  
    // The conversion failed.  
} 
+0

Boost看起來很棒。我會玩弄一下,看看我得到了什麼。我可能會切換到'boost :: program_options',看起來它會起作用。儘管'lexical_cast'現在可以工作:)謝謝! – Amit

11

ato*家庭很糟糕,並且不能正確表示錯誤。在C++中,您希望使用boost::lexical_cast或完整的命令行解析器,如boost::program_options

+0

boost :: program_options +1使事情變得更容易。 – GWW

0

您仍然可以使用atofatoi

#include <cstdlib> 

int main(int argc, char* argv[]) { 
    float f = std::atof(argv[1]); 
    int i = std::atoi(argv[2]); 
} 

但是,您可以使用更通用的設施,如boost::lexical_cast

+0

用ato?()很難檢測錯誤。當我錯誤地輸入'command '15 2'plop'時,它會完全錯過2。反對這個論點是「人們並不那麼愚蠢」。我同意但是腳本是,並且在參數被替換並且應該檢查這些事情的腳本中使用了很多命令。 –

2

如果你的意思是使用流和>>操作,您可以使用stringstream

double a; // or int a or whatever 
stringstream(argv[1]) >> a; 

您需要包括<sstream>

4

如果你想保存自己解析CMD行參數的辛勤工作你自己可以隨時使用圖書館,如boost::program_options