简体   繁体   English

通过命令行参数传递文件名与使用字符串文字in-code

[英]Passing a filename through a command-line argument vs. using a string literal in-code

The following bit of code seems to interpret the slash in the passed filename differently, depending on whether it was passed as a command line argument, or hardcoded by means of a literal. 下面的代码似乎以不同的方式解释传递的文件名中的斜杠,具体取决于它是作为命令行参数传递,还是通过文字硬编码。 If the image filename C:\\kimba.jpg is passed in as a command line argument, it works fine: 如果图像文件名C:\\kimba.jpg作为命令行参数传入,它可以正常工作:

int main( int argc, char** argv ) 
{
    IplImage* img = cvLoadImage(argv[1]);
    //IplImage* img = cvLoadImage("C:\kimba.jpg", 1);

    // ...

    return 0;
}

If, on the other hand, I uncomment the second line and comment the first, the same filename causes an exception in that line. 另一方面,如果我取消注释第二行并注释第一行,则相同的文件名会在该行中引发异常。 I do not know how cvLoadImage() is implemented, but it seems (according to the debugger) that in both cases the same content is being passed to the function. 我不知道如何实现cvLoadImage() ,但似乎(根据调试器)在两种情况下都将相同的内容传递给函数。 So why does the hardcoded filename cause an exception and not the command-line argument? 那么为什么硬编码的文件名导致异常而不是命令行参数呢?

你需要用反斜杠来逃避反斜杠:

IplImage* img = cvLoadImage("C:\\kimba.jpg", 1);

the '\\' character is the escape character in C++. '\\'字符是C ++中的转义字符。 To get a '\\' character literal, you need to escape it (note the double '\\'): 要获得'\\'字符文字,您需要将其转义(注意双'\\'):

IplImage* img = cvLoadImage("C:\\kimba.jpg", 1);

HTH. HTH。

使用"C:\\\\kimba.jpg" - \\用于转义特殊字符,例如\\n

Backslash in string literals is an escape character, while in command line argument it is interpreted as-is. 字符串文字中的反斜杠是转义字符,而在命令行参数中,它被解释为-is。 So in the second case the file is not found and you get an exception. 所以在第二种情况下找不到文件,你得到一个例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM