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.
Related
This question already has answers here:
String plus Char - what is happening?
(5 answers)
Closed 8 months ago.
#include <iostream>
#include <conio.h>
#include <stack>
#include <string>
using namespace std;
int main{
string h = "";
h = ("" + 'a');
cout << h;
return 0;
}
Output: "nity\VC\Tools\MSVC\14.29.30133\include\xstring"
I am honestly clueless as to what to do. I've never had this happen before.
Note: I've found a way to avoid this by appending the char like this:
string g="";
g+='a';
Regardless, why is this?
"" is a literal of type const char[1], which is the identical as const char* in most regards. 'a' is a literal of type char, which is really just an integer type. So if you do "" + 'a', you will get a pointer to 'a' (=97 in ASCII) characters after wherever the compiler decides to put the "". Which is then converted to an std::string.
In the working example, you convert the "" literal to std::string first, then add a char to it. std::string overloads the + and += operators, so it will produce a reasonable result.
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 4 years ago.
Improve this question
I have a vector of string object :
I need to convert it into char* using stringstream and store char* in a vector.
is it right way to do it?
//! strvector contain string objects and newcharvector needs to be populate.
for(int i =0 ; i < strvector.size(); i++)
{
std::string &obj = strvector[i];
std::stringstream ss;
char* str;
ss << obj;
ss >> str;
newcharvector.push_back(str);
}
A char* is a pointer that points to a memory area that contains the string.
In your example: Where is this memory/the string?
Of course, stringstream (which should not be used anymore, use istringstream or ostringstream) internally stores the string, and you could retrieve the string from it, but the moment that the stringstream object is deleted, the internal string is deleted and your char* pointer points to free/unused memory (which will most likely be re-used by the next instance of the stringstream variable).
For storing a char* in a vector you would have to take a tour of the dynamic memory allocation wonderland. Don't (yet).
Why don't you store std::strings in your vector?
Don't use raw pointers!
#include <vector>
#include <string>
#include <iostream>
#include <memory>
int main()
{
std::vector<std::string> strvector{ "foo", "bar", "baz", "qux", "thud" };
std::vector<std::shared_ptr<char[]>> newcharvector;
for (auto const &s : strvector) {
newcharvector.push_back(std::shared_ptr<char[]>(new char[s.length() + 1]));
std::strcpy(newcharvector.back().get(), s.c_str());
}
for (auto const &s : newcharvector)
std::cout << s << '\n';
}
Is it right way to do it?
It's rather roundabout. Better just use c_str() to get the string representation represented as char*, and then use strdup() to persist that string (if that's necessary, because the pointer returned by c_str() is invalid as soon as you modify the std::string or it goes out of scope)
std::vector<std::string> strvector{ "foo", "bar" };
std::vector<char*> pointers;
for (std::string &s : strvector) {
pointers.push_back(_strdup(s.c_str()));
}
for (char* p : pointers) {
printf("string: %s\n", p);
}
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
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'm having trouble using type char. When I initialize my ID and Name in my struct by a constructor, why am I getting this error message? "expression must be a modifiable lvalue".
struct Staff
{
char ID[8];
char Name[30];
Staff()
{
ID = "";
Name = "";
}
};
Since this question is tagged C++ and the code make uses of C++ only features (such as constructors), I'm going assume you have mistakenly confused C with C++ in your title.
Don't use char arrays when you really mean strings. Use std::string instead:
struct Staff {
std::string ID;
std::string Name;
};
In this way the default constructor will behave as expected and you won't even need to specify it. The only additional line you'll need is the one that includes the necessary header:
#include <string>
on the very top of the file.
char in C and C++ is just another numeric type, like int, but smaller (generally one byte). An array of chars is not special -- it's basically a raw hunk of memory. A string literal is internally an array of chars as well, but C++ has no built-in support for copying arrays with operator= -- you have to copy the bytes yourself, for example via the (deprecated) strcpy C function (include cstring).
In C++, the usual way to deal with strings is to use std::string (include string), which is a class that wraps the string's bytes for you, and implements string copying, comparison, etc. in a clean, intuitive fashion.
You're also missing a semicolon at the end of the Staff structure, which will cause some interesting compile errors :-)
You cannot change the value of ID or Name since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*):
const char *ID;
const char *Name;
Or use memset:
memset(ID, '\0', sizeof(ID));
memset(Name, '\0', sizeof(Name));
This will "initialize" your char arrays.
You can do the same to assign a string to the array using strncpy
strncpy(Name, "John Doe", sizeof(Name)-1);
The -1 accounts for the null terminating character.
What you need to do is
struct Staff
{
char ID[8];
char Name[30];
Staff() :
ID{0}, // Null terminate the array same as, ID[0] = 0;
Name{0} // Null terminate the array same as, Name[0] = 0;
{
}
};
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.