I'm trying to write a program which I'll be able to start with custom arguments. Like in this example "program.exe -width 1920 -height 1080". I wrote a simple code, which should work.
#include <iostream>
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
if (argv[i] == "-width")
{
std::cout << "Width: " << argv[++i] << "\n";
}
else if (argv[i] == "-height")
{
std::cout << "Height: " << argv[++i] << "\n";
}
}
return 0;
}
And this program doesn't work. It's not displaying anything. I also tried checking this code line by line with debugger, but when argv[i] == "-width"
it just skips it.
Is there a way to fix it or there are just some other methods of doing this?
You are comparing pointers, not strings. To compare strings via ==
, you should use std::string
.
Also you should check if the elements argv[++i]
exists.
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
if (argv[i] == std::string("-width") && i + 1 < argc)
{
std::cout << "Width: " << argv[++i] << "\n";
}
else if (argv[i] == std::string("-height") && i + 1 < argc)
{
std::cout << "Height: " << argv[++i] << "\n";
}
}
return 0;
}
You can also use the s suffix
cout << ("wilson" == "wilson"s) << endl;
output:
1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.