I'm using a function to download a file.
void downloadFile(const char* url, const char* fname) {
//..
}
This is called like :
downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt");
This working fine.
But I want to change the URL to be a value from an array. The array stores encrypted values which when decrypted are strings, so I get the issue error: cannot convert ‘std::basic_string<char>’ to ‘const char*’
I've tried:
string test = decode(foo[5]);
const char* t1= test.c_str();
downloadFile(t1 "filename.txt", "/user/tmp/file.txt");
downloadFile(t1 + "filename.txt", "/user/tmp/file.txt");
and
downloadFile((decode(foo[5]).c_str()) + "filename.txt", "/user/tmp/file.txt");
which gives:
error: invalid operands of types ‘const char*’ and ‘const char [17]’ to binary ‘operator+’
What am I doing wrong ?
Thanks
C-strings can't be concatenated with +.
Use std::string::+ instead:
downloadFile((test + "filename.txt").c_str(), "/user/tmp/file.txt");
Note that c_str only returns a pointer to the std::string's internal character array, so it's valid only during the execution of the downloadFile function.
Try this:
downloadFile((decode(foo[5]) + "filename.txt").c_str(), "/user/tmp/file.txt");
The operator+ is not defined for char arrays.
The main problem in your code is that you are trying to use operator+ to concatenate raw C strings (i.e. raw const char* pointers, or raw char [] arrays), which doesn't work.
In C, you should use proper library functions (like strncat or safer variants) to do that; but since you are using C++, you can do better, and write easier code: just use a C++ string class, like std::string.
In fact, the C++ standard library offers convenient overloads for operator+ that work with std::string, so you can concatenate C++ strings in an easy, intuitive and safe way; for example:
// Build your URL string
std::string test = decode(foo[5]);
std::string url = test + "filename.txt";
// Use std::string::c_str() to convert from C++ string
// to C raw string pointer const char*
downloadFile(url.c_str(), "/user/tmp/file.txt");
Related
I read data from a file and I wanted to use on of its values in a function. This is a custom function, I am programming TOOLKIT for Creo Parametric.
Well, that function is expecting a 'xrstring' but I have a std::string.
How to I convert one into another?
I've tried writing xrstring test_var = xrstring(std_var);
And it doesn't work.
//definition of xrstring
typedef const char *xrstring;
#define xstringuninit ((xrstring) 2)
#define xstringnil ((const char *) 1)
#define xwstringnil ((const wchar_t *) 1)
#define xwstringuninit ((const wchar_t *) 2)
//definition of pfcCreateStringParamValue
pfcParamValue_ptr pfcCreateStringParamValue (xrstring Value);
error C2664: 'pfcParamValue_ptr pfcCreateStringParamValue(xrstring)': cannot convert argument 1 from 'std::string' to 'xrstring'
The xrstring you speak of is const char * or a C-style string.
std::string comes with a convenient function to convert a std::string to C-style string - std::string::c_str()
Hence, here is the right way to do what you want to do:
xrstring test_var = std_var.c_str();
Also, there does not exist a direct const char * to std::string cast. The Standard Library string is not a mere pointer-to-char. It contains other information like string-length as well.
I personally would recommend you to declare xstring as a class if you want to do a conversion like xrstring test_var = xrstring(std_var);, and make a suitable constructor for the conversion.
I am now using C++ to program a robot using PROS. Pros has a print function, which is taking in a const char*. Now, I'm using lvgl to create my own screen, and I want to replicate the print function. Like the printf() functions, I want it to include variadic params to do the %d effect (so it converts all the %? to the corresponding values). The problem now is about the conversions between functions. I wanted to make a convert function to convert a string and the variadic params into a complete string. I need to input is a string which is like "hey" and I'm unsure what the type name should be. I need to be able to get size, search in it for %ds but I need the function to return a const char* to pass onto the lvgl to pring on the screen. I am having a bad time trying to convert a string into an const char* for the out put of the convert function.
Also, I tried using the input type as a char*, and when I input a string like "hello" is says a error [ISO C++11 does not allow conversion from string literal to 'char ' [-Wwritable-strings]]. But instead, when is use a const char, the error disappears. Anyone knows why?
Thanks everyone for your kind help!
char* and const char* are two flavours of the same thing: C-style strings. These are a series of bytes with a NUL terminator (0-byte). To use these you need to use the C library functions like strdup, strlen and so on. These must be used very carefully as missing out on the terminator, which is all too easy to do by accident, can result in huge problems in the form of buffer-overflow bugs.
std::string is how strings are represented in C++. They're a lot more capable, they can support "wide" characters, or variable length character sets like UTF-8. As there's no NUL terminator in these, they can't be overflowed and are really quite safe to use. Memory allocation is handled by the Standard Library without you having to pay much attention to it.
You can convert back and forth as necessary, but it's usually best to stick to std::string inside of C++ as much as you can.
To convert from C++ to C:
std::string cppstring("test");
const char* c_string = cppstring.c_str();
To convert from C to C++:
const char* c_string = "test";
std::string cppstring(c_string);
Note you can convert from char* (mutable) to const char* (immutable) but not in reverse. Sometimes things are flagged const because you're not allowed to change them, or that changing them would cause huge problems.
You don't really have to "convert" though, you just use char* as you would const char*.
std::string A = "hello"; //< assignment from char* to string
const char* const B = A.c_str(); //< call c_str() method to access the C string
std::string C = B; //< assignment works just fine (with allocation though!)
printf("%s", C.c_str()); //< pass to printf via %s & c_str() method
I compiled .cc file whith g++ on linux ubuntu, I want to use srtcmp() function to compare two strings. the strings are not constant. user will give both of them, but I get this error:
error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
and this is my code:
if (!strcmp(a[i].personalNo,pcode)){
#some code
}
which function can I use instead of strcmp() to compare two strings?
The problem isn't on the function but on the way that you're using it.
int strcmp ( const char * str1, const char * str2 );
strcmp takes two const char * arguments.
The error tells you that you are giving the function a char so the problem is on the types of personalNo and/or pcode. Your mistake is probably on the declaration of the type of those two variables. You would want to change their type to char * as char only stores one character while char * is an array of characters.
Also, an another way to compare two strings in C++ is to use std::string. Then you can just do the following (provided that both personalNo and pcode are std::string:
if (a[i].personalNo != pcode){
#some code
}
I use rapidjson to read JSON files, and some of the values are string. Now, rapidjson's GetString() method returns a const char *. I'd like to store this in std::string, though. I've tried this:
const char* foo = d["foo"].GetString();
printf("Foo: %s\n", foo); // Prints correctly
std::string fooStr(foo);
printf("FooString: %s\n", fooStr); // Gibberish
How do I get the correct std::string?
You can't pass std::string directly to printf. It's a C-style variadic function, that only works with C-compatible types, not (non-trivial) C++ classes. In particular, the %s specifier requires its matching argument to be a pointer to C-style string (a zero-terminated character array), of type const char *.
You can either use a C++ stream:
std::cout << "FooString: " << fooStr << '\n';
or extract a C-style pointer from the string:
printf("FooString: %s\n", fooStr.c_str());
You should also enable compiler warnings; that should tell you exactly what's wrong.
To convert string to const char* use string::c_str()
This is a basic understanding concepts related question.
Working using: Embarcadero C++ Builder
What is the difference between:
opendir("C:\\XYZ")
and
String file = "C:\\XYZ";
opendir(file);
Aren't both strings?
The first one works but the sexond gives me error:
E2034 Cannot convert Unicode String to ' const char*'
In a case where I take input from the user I can only pass a string. How do i pass the whole path?
first one is a const char*, second one is a std::string. The opendir function accepts only const char* in your case and thus cannot convert std::string to const char* on its own. you can get the function to work by opendir(file.c_str()); .
No. A String is not a char array. opendir needs a char array.
opendir() expects an 8bit narrow const char* as input. When you pass a narrow literal to opendir(), you are passing it a const char[], which implicitly degrades to const char*, and all is fine.
String is System::String, which is a typedef for System::UnicodeString, which is Embarcadero's UTF-16 encoded string class (similar to std::wstring, but with different semantics). When you pass a String to opendir(), you get a conversion error.
To pass a String value to opendir() (or any other function that expects char*), you need to first convert it to a System::AnsiString, and then use AnsiString::c_str() to get a char* from it, eg:
String file = "C:\\XYZ";
opendir(AnsiString(file).c_str());