[英]Running a program from command prompt and using argv in C++
我編寫了一個程序,它從 argv[1] 獲取文件名並對其進行操作。 從 Visual Studio 調試時,我從項目選項>>調試>>命令 arguments 傳遞文件名,它工作正常並正確打印所有結果。
但是當從命令提示符嘗試時,我 go 到項目目錄/調試我輸入
program
它工作正常並在同一個 window 中打印“沒有有效的輸入文件” (這是我的錯誤處理技術)
但是當我輸入
program test.txt
它什么也不做。 我認為代碼沒有問題,因為它在調試器中運行良好。
代碼:
int main(int argc, char *argv[])
{
int nLines;
string str;
if(argv[1]==NULL)
{
std::cout << "Not valid input file" << endl;
return 0 ;
}
ifstream infile(argv[1]);
getline(infile,str);
nLines = atoi(str.c_str());//get number of lines
for(int line=0 ;line < nLines;line++)
{
//int currTime , and a lot of variables ..
//do a lot of stuff and while loops
cout << currTime <<endl ;
}
return 0 ;
}
您不檢查文件是否已成功打開,getline 是否返回錯誤代碼,或者字符串到 integer 的轉換是否失敗。 如果發生任何這些錯誤,我猜是這種情況, nLines
將等於0
,不會執行任何循環,程序將退出並返回代碼0
。
這段代碼對我在命令行上運行正常。
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int nLines;
string str;
if(argv[1]==NULL)
{
std::cout << "Not valid input file" << endl;
return 0 ;
}
else
std::cout << "Input file = " << argv[1] << endl;
}
Output:
C:\Users\john.dibling\Documents\Visual Studio 2008\Projects\hacks_vc9\x64\Debug>hacks_vc9.exe hello
Input file = hello
順便說一句,這段代碼是危險的,充其量是:
if(argv[1]==NULL)
在嘗試取消引用可能是野生指針之前,您可能應該檢查argc
的值。
該文件可能包含無效的數字第一行(可能以空格或BOM開頭)。
這可以解釋沒有 output,因為如果nLines == 0
則應該沒有 output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.