Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I don't have much experience in C++. I have a function std::string Exec(char* cmd). It runs for cout<<Exec("hello!"), but it doesn't run for std::string: invalid conversion from ‘const char*’ to ‘char*. I was wondering how I can fix it.
std::string s="hello";
char * c = s.c_str();
Exec(c);
Well that's because c_str() returns a const char * and not a char *
Just change the line to:
const char * c = s.c_str();
and the function declaration to
std::string Exec(const char* cmd)
Like noted before and you're good to go.
See it live here.
You need to change your prototype to this:
std::string Exec(const char* cmd)
since you want to pass a const char* as an argument.
Otherwise, you can pass a char* as an argument.
That's why your's cout<<Exec("hello!") works, because the argument is passed as non-const!
The correct signature for what you're attempting to do would be
std::string Exec(const char* cmd)
because in either cases you're passing a string constant to it. Even if the Exec("hello") case compiles, that doesn't mean it's safe to use:
#include <iostream>
using namespace std;
std::string Exec(char* cmd) {
cout << cmd;
cmd[0] = 'S'; // Undefined behavior
cout << cmd;
return std::string("");
}
int main() {
Exec("hello");
return 0;
}
http://ideone.com/ZY6Atr
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to split a path from Windows by '' , but when I'm running my program crashes.
Here's a small example:
char*s = "C:\\windows\\system32\\calc.exe";
char*pch;
pch = strtok(s,"\\");
while(pch!=NULL){
printf("%s\n",pch);
pch = strtok(NULL,"\\");
}
I can make a search manually, but I think it's easier way than that.
Thanks in advance.
You need a mutable string. A string literal is immutable. Trying to change a string literal will result in undefined behavior. Instead of char *s = "C:\\windows\\system32\\calc.exe"; (pointer to string literal) you can simply use a array of chars char s[] = "C:\\windows\\system32\\calc.exe";. This will copy the string literal into a mutable array.
The only problem is that you have to use char s[] insead of char* s
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char s[] = "C:\\windows\\system32\\calc.exe";
char * pch;
pch = strtok (s,"\\");
while (pch != NULL) {
printf ("%s\n",pch);
pch = strtok (NULL, "\\");
}
return 0;
}
I prefer not to use strtok because it can only access by char*.
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
template <class Container>
void split(const std::string& str, Container& cont, char delim = '\\')
{
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delim)) {
cont.push_back(token);
}
}
After I read all the comments, I realized that I can make a copy of that path and replace all '\' with another character, like '*', then you can use strtok(modifiedCopy,"*") function without any problem. Anyway, thanks to everyone in the comments section.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to convert a result string that I get by doing some data manipulation, eg:
std::string result = std::string(/* num_max */, '0').append(myDataModule->getId().c_str());
I'm getting an id from getId() (which returns an AnsiString) on my TDataModule, converting that to a std::string using AnsiString::c_str(), and appending that with zeros on the left (spaces that will remain) to my result string.
I need to use the value of result in a function that receives a char *:
void receiver(char * data, int num){
... <- A lot of code here
if( data != NULL )
{
strcpy( rdData, data); <-- rdData is an char *
...
}
}
Basically, in this function it will copy data to rdData and do some verifications.
When I run the code, an error appears when I call this function:
candidate function not viable: no known conversion from 'std::string' (aka 'basic_string') to 'char *' for 1st argument
When I run the code, an error appears when I call this function:
candidate function not viable: no known conversion from 'std::string' (aka 'basic_string') to 'char *' for 1st argument
You did not show the actual code that is trying to pass the std::string to the receiver() function, but the error message is very clear. You simply cannot assign a std::string directly to a non-const char*, which is exactly what the compiler is complaining about.
However, you can get a const char* from a std::string using its c_str() method, and then you can const_cast that to a char* (as long as the function does not try to modify the char data), eg:
std::string result = ...;
receiver(const_cast<char*>(result.c_str()), static_cast<int>(result.size()));
Or, you can simply use &result[0] instead (which is guaranteed in C++11 and later to be contiguous and null-terminated), or you can use result.data() in C++17 and later, eg:
std::string result = ...;
receiver(&result[0]/*result.data()*/, static_cast<int>(result.size()));
Or, you could simply change result from std::string to AnsiString, as its c_str() method returns a non-const char*, eg:
AnsiString result = AnsiString::StringOfChar('0', 8) + myDataModule->getId();
receiver(result.c_str(), result.Length());
Either way, if receiver() only needs to read from data and not modify its content, then it should be changed to take data as a const char* instead (especially since that is what strcpy() expects anyway), eg:
void receiver(const char * data, int num)
Then you can use result.c_str() as-is, no trickery, whether result is an AnsiString or a std::string.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have a function that receives two parameters: one input and one input/output, the first is a constant type string and the second is a reference to an array of unsigned char characters, the problem is that when I pass the address of the array, it generates this error when compiling initial value of reference to non-const must be an lvalue
This is the code where I call the function:
unsigned char in[20];
string str = "ABCDEF123456";
function(str, &in); //ERROR HERE
And this is the function:
void function(const std::string &str, unsigned char *&in)
{
in = new unsigned char[str.length() / 2];
for (int aux = 0, tam_str = str.length(); aux != tam_str; aux += 2)
{
std::stringstream ss;
ss << std::hex << str.substr(aux, 2);
int valor;
ss >> valor;
in[aux / 2] = valor;
}
}
NOTE: The purpose of the function is to convert the content of the variable str (hexadecimal values) to the array of characters in.
The type of the argument declaration, and the type of the object that you pass do not match.
Answer for new question:
Like in the old version, you pass a pointer to an array of 20 unsigned char. But the argument type is a reference to a pointer to a unsigned char. That doesn't work.
To call the function, you must have a pointer to an unsigned char:
unsigned char* ptr = in;
function(str, ptr);
On the other hand, it makes no sense to pass a pointer by reference unless you modify the pointer - which you don't do. So, it might be more sensible to pass a copy of the pointer instead:
void function(const std::string &str, unsigned char *in);
function(str, in);
Old answer:
void function(const std::string &str, std::vector<unsigned char> &in)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
unsigned char in[20];
^^^^^^^^^^^^^^^^^^^^
function(str, &in); //ERROR HERE
^^^
The function has been declared to accept a reference to a std::vector<unsigned char> object. You attempt to pass an address to an array of 20 unsigned char as the argument. That doesn't work.
To call the function, you need to have a vector object:
std::vector<unsigned char> in;
function(str, in);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Could you tell me the way to pass the value (char * a) to the value (const char* b)?
For example,
char * str = "Tokyo";
const char *;
"char = str" is OK?
char * str = "Tokyo";
In c++, this is not allowed †. You may not assign a const array (such as a string literal) to a non-const pointer.
const char *;
This is not allowed, because a variable declaration must have a name (unless it's a function argument).
const char *str = non_const_pointer_or_array;
The above is OK in c++.
† Implicit conversion from const to non-const is allowed in c but typically discouraged by compiler warnings. It was deprecated in c++ and not allowed at all since c++11.
In c++, it should just work. Native/Builtin types are automatically convertible to more const, but not to less const.
Therefore:
void foo(const char*) {
}
int main() {
char s[] = {'x', 'y', 'z', '\0'};
foo(s); //Compiles fine.
return 0;
}
This compiles fine, however the other way around, one has to use a const_cast. One should however not lie to the compiler and indicate that something is non const, while in actual fact it is const, as the program behavior in that case is undefined (one cannot know what the behavior of the program might be). const_cast is typically only used when old APIs require char* arguments despite it not modifying the arguments, and should never be used to "lie" to the compiler.
Example:
void some_old_api(char*){}
int main() {
const char* cs = "xyz";
some_old_api(const_cast<char*>(cs));
return 0;
}
A character array hard-coded in your program is a const char*, so you can declare it as const char* str = "Tokyo";Or, when you do have a char* str, you can cast it as follows: const char* myconst = (const char*) str;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i have std::string pointer and i like to copy its value to ordinary std::string
i can't find quick and fast way to do it .
i have this :
int main ()
{
std::string * pStr = new std::string("hello")
std::string strNew = pStr->??? // how to convert ?
return 0;
}
Dereference:
std::string strNew = *pStr;
Two ways:
std::string strNew = pStr->c_str(); // Be careful of `\0` with in the string
or
std::string strNew = *pStr;
The second is better, because C-style string can not represent std::string correctly. It ends a string at first \0 and ignores trailing.