从命令提示符运行程序并在 C++ 中使用 argv;
我编写了一个程序,它从 argv[1] 获取文件名并对其进行操作。 从 Visual Studio 进行调试时,我从项目选项>>调试>>命令参数传递文件名,它工作正常并正确打印所有结果。
但是,当从命令提示符尝试时,我转到项目/调试的目录,我输入
program
它工作正常,并在同一窗口中打印 “没有有效的输入文件” (这是我的错误处理技术)
但当我输入时
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 ;
}
I have written a program that takes the filename from argv[1] and do operations on it .
When debugging from visual studio I pass the filename from project options>>debugging>>command arguments and It works fine and prints all results correctly .
But when trying from the command prompt , I go to the dir of project/debug the I type
program
It works fine and prints "No valid input file" in the same window (Which is my error handling technique)
but when i type
program test.txt
It just does nothing . I think no problem in code because it works fine from the debugger .
Code :
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 ;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不检查文件是否已成功打开,getline 是否返回错误代码,或者字符串到整数的转换是否未失败。如果发生任何这些错误(我猜是这种情况),
nLines
将等于0
,不会执行任何循环,程序将退出并返回代码0 。
You don't check if file was successfully opened, whether getline returned error code or not, or if string to integer conversion didn't fail. If any of those error occur, which I guess is the case,
nLines
will be equal to0
, no cycles will be performed and program will exit with return code0
.这段代码对我在命令行上运行来说是正确的。
输出:
顺便说一句,这段代码充其量是危险的:
您应该在尝试取消引用可能为野的指针之前检查 argc 的值。
This code worked correctly for me running on the command line.
Output :
By the way, this code is dangerous, at best:
You should probably be checking the value of
argc
before attempting to dereference a possibly-wild pointer.该文件可能包含无效的数字第一行(可能以空格或 BOM 开头) 。
这可以解释没有输出,因为如果 nLines == 0 则不应有输出
The file probably contains an invalid numeric first line (perhaps starting with a space or the BOM).
That would explain no output, since if
nLines == 0
no output should be expected