Reputation: 59
I have function like below:
int main(int argc, char *argv[])
{
}
I want to find a character(dot character) in argv[1]
. I tried to convert char*
to string like below :
std::string para2="";
if(argc==2 && argv[1]!=NULL)
{
para2 = string(argv[1]);
}
but para2
show strange characters with print command and find function is not working properly. Please guide me how to find character in char*
type.
Thanks
Upvotes: 1
Views: 3253
Reputation: 141
You may use the wrong printf. You can use std::cout to output the para2 but not use printf for the string type. As printf can only print out original type like int, double, float, ulong, char, char* etc.
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
std::string para2="";
if(argc==2 && argv[1]!=NULL)
{
para2 = std::string(argv[1]);
std::cout<<para2<<std::endl;
}
return 0;
}
You can refer to "printf" on strings prints gibberish and "printf" on strings prints gibberish.
If you want to find the specified string in char*, you can use strstr() function to do such things. And string::find can also do the find work, you can refer to http://www.cplusplus.com/reference/string/string/find/
For string::find function, the return value is size_t type. And the return value returns the position of the first character of the first match. If no matches were found, the function returns string::npos.
You should always use string::npos for the check condition but not with 0.
Upvotes: 0
Reputation: 43004
Some notes follow:
Note #1:
std::string para2="";
When you construct a string, the default constructor initializes an empty string, so you don't need the =""
part: std::string para2;
is just fine.
Note #2:
if(argc==2 && argv[1]!=NULL)
{
para2 = string(argv[1]);
}
When you assign from char*
to std::string
, you can just use operator=
overload, without the explicit string
part:
para2 = argv[1];
Basing on some request in some comment to your question, you can use std::string::rfind
to check for some extension, e.g.:
#include <iostream>
#include <string>
int main(int argc, char * argv[])
{
std::string param2;
if (argc == 2)
{
param2 = argv[1];
}
std::cout << param2 << std::endl;
if (param2.rfind(".jpg") != std::string::npos)
{
std::cout << "JPEG file." << std::endl;
}
}
Upvotes: 1
Reputation: 7620
You probably are building your EXE as UNICODE.
Try setting the "Character set" to "Use Multi-Byte Character Set" in Properties->General
Upvotes: 0