2017-10-07 49 views
0

我對C++有點新,所以很抱歉,如果這個問題很明顯,但我碰到了一些障礙。我想要做的是有一個命令提示符來執行某些操作。你把簡單的命令,如timer down 10這將啓動一個計時器倒計時,我已經做得很好。我檢測了每個單詞的方法是用這樣的:多個字命令C++

string cmd1; 
string cmd2; 
int cmd3; 
cin >> cmd1 >> cmd2 >> cmd3; 

除了我想有一個字的命令,並用這個系統,我真的不能做這工作正常。如果我想,例如,help作爲命令,它使我輸入2個字符串和一個int,當我只想輸入1個字符串。但我想要具有特定的命令,可以是完整的2個字符串和一個int或只是一個字符串。

+0

我建議你閱讀一切轉換成字符串,然後做解析後。你可以使用std :: getline。 –

+0

Trevor Hickey我確實考慮過這一點,但我不確定如何閱讀特定的單詞。任何建議如何做到這一點?謝謝 – TriDeapthBear

+0

@TriDeapthBear什麼?正如在評論中所建議的那樣 - 用'std :: getline'讀完整行,然後在該行上解析。有什麼不清楚的呢? –

回答

0

使用getline將整個命令存儲在單個字符串中。

String command; 
std::getline (std::cin,command); 

現在,您可以使用以下代碼將命令拆分爲令牌字。

int counter =0; 
string words[10]; 
for (int i = 0; i<command.length(); i++){ 
    if (command[i] == ' ') 
     counter++; 
    else 
     words[counter] += command[i]; 
} 
+0

謝謝!我花了一點時間來理解代碼,但它有效!謝謝您的回答! – TriDeapthBear

0

您需要使用getline讀取該命令,然後將其拆分爲令牌。檢查getline的功能,谷歌拆分線到令牌C++

0

你可以逐行讀取輸入行,然後每行分成std::vector包含每個命令後它的參數:

void command_help() 
{ 
    // display help 
} 

void command_timer(std::string const& ctrl, std::string const& time) 
{ 
    int t = std::stoi(time); 

    // ... etc ... 
} 

int main() 
{ 
    // read the input one line at a time 
    for(std::string line; std::getline(std::cin, line);) 
    { 
     // convert each input line into a stream 
     std::istringstream iss(line); 

     std::vector<std::string> args; 

     // read each item from the stream into a vector 
     for(std::string arg; iss >> arg;) 
      args.push_back(arg); 

     // ignore blank lines 
     if(args.empty()) 
      continue; 

     // Now your vector contains 

     args[0]; // the command 
     args[1]; // first argument 
     args[2]; // second argument 
     // ... 
     args[n]; // nth argument 

     // so you could use it like this 

     if(args[0] == "help") 
      command_help(); // no arguments 
     else if(args[0] == "timer") 
     { 
      if(args.size() != 3) 
       throw std::runtime_error("wrong number of arguments to command: " + args[0]); 

      command_timer(args[1], args[2]); // takes two arguments 
     } 
    } 
}