2016-01-25 72 views
-1

在我的程序開始時,它應該從控制檯獲取輸入文件路徑和輸出文件路徑。 但是,如果用戶不給出所需數量的參數或錯誤的參數(例如空格或沒有「.txt」),它應該給用戶第二次機會在不退出程序的情況下輸入這些參數。可能嗎?如何從Windows控制檯檢查程序啓動參數?

int main(int argc, char* argv[]) 
{ //and here should be something to check if the user entered parameters correctly 
//(number and if they look like a path) and give a user another try if this is wrong 
//(so that user enter them from console again) 

string path_open(argv[1]); 
    strin path_out(argv[2]); 
+1

***是否有可能?***是的,這當然是可以的。同樣在你的示例代碼中,你應該在使用argv [1]之前檢查argc ... – drescherjm

+1

是的,可以再次詢問用戶。但爲什麼你會考慮這個?如果用戶輸入垃圾,請寫入錯誤消息並退出。編寫代碼沒有令人信服的理由,爲用戶提供了第二次機會。如果他們需要第二次機會,讓他們再次調用您的程序。 – IInspectable

回答

1

是的,這是可能的,但是......很奇怪。如果你打算讓你的程序要求輸入,爲什麼不把放在一個循環中,直到你得到正確的輸入?最後,我會做一個或另一個:

  1. 獲取命令行輸入(和,@IInspectable建議在評論中,如果它是無效的,退出程序);或
  2. 有程序要求輸入遞歸,直到用戶給出有效的輸入。

在命令行輸入

int main(int argc, char* argv[]) 
{ 
    // sanity check to see if the right amount of arguments were provided: 
    if (argc < 3) 
     return 1; 
    // process arguments: 
    if (!path_open(argv[1])) 
     return 1; 
    if (!path_out(argv[2])) 
     return 1; 
} 

bool path_open(const std::string& path) 
{ 
    // verify path is correct... 
} 

程序要求輸入:

int main() 
{ 
    std::string inputPath, outputPath; 
    do 
    { 
     std::cout << "Insert input path: "; 
     std::getline(std::cin, inputPath); 
     std::cout << std::endl; 
     std::cout << "Insert output path "; 
     std::getline(std::cin, outputPath); 
    } while (!(path_open(inputPath) && path_out(outputPath))); 
} 

當然你會驗證輸入分開的情況下,他們進入了一個有效的輸入路徑但無效的輸出路徑,但您獲得了要點。

相關問題