I need to convert a char array to string to use the string on a finite automaton, i've tried char[50]=string but it copies it indeed but has rubbish on in, char array has to be determinated, no more than 6 letters and i can't find another way, at least on C++ to make it, thanks a lot.
To assign a C style string (char array) to a std::string, you can use the following code:
std::string foo = c_style_string;
In addition, the variable on the left-hand side of the assignment operator (equal sign) is changed to the value of the variable on the right-hand side. char[50] = string will not compile.
Convert char array to string
char cArray[12] = "hello world";
string str(cArray);
Related
This is a constructor that I found from the internet, but it didn't have enough descriptions so I couldn't understand how it's even possible for this constructor to have string as a parameter.
For instance, if I say MyString str1("hello world this "hello world" goes into the constructor, but I have no idea how this string can get into this const pointer parameter. Can anyone explain how this is possible?
MyString::MyString(const char* str) {
string_length = strlen(str);
string_content = new char[string_length];
for (int i = 0; i != string_length; i++) string_content[i] = str[i];
}
When you get a const char* you are getting what is called a C string, which is a pointer to an array of characters that ends with a special value '0/' which you dont have to type. All strings that you write as literals in the code are of this form.
Dont confuse C strings with the C++ class strings (that works with C strings underneath) since are different.
So what is happening is the constructor doesn't actually receive a string, it receives a pointer that points to something of type char (and what is a string if not a sequence of chars, and I mean the concept of string and not the string object in C++ itself).
When you do "MyString str1("hello world")" what is actually passed to the constructor is a pointer that points to the first char of the string, in this case the "h" char.
I'm having trouble understanding some particular behaviour of assignment in strings.
//method 1
std::string s;
s+='a' //This works perfectly
but
//method2
std::string s;
s="" + 'a';//This gives unexpected value
Why 2nd method gives unexpected value ? From what I've read string default constructor initialise string variable as empty string, if no constructor is specified. And s+='a' should be same as s=s+a. So why isn't the method 2 same as method 1?
And one more query on the same topic , if we can't initialise a string with char literal then how can we assign a char literal to it?
std::string s2='a'//gives error while compiling
whereas
std::string s2;
s2='a'//works perfect
From what I understand is we cannot initialise a string variable by char variable because string constructor needs argument of the type(const char *). Why is there not any such restriction while assigning?
For your first query ,
method 1 works perfectly cause in this method you are adding string object type and char literal .
and s+='a' , is indeed same as s=s+'a'
focus on the fact that s is string object type rather than string literal.
In the 2nd method , you are adding string literal
and char literal . Focus on the difference between the two , In first method there is string object you can add string or char literals to string object type,its one of the features provided by string object type . But you cant add simply add the literals with each other.In c++ , however "StringLiteral1" "StringLiteral2" , will result in the concatenation of the two string literals.
for 2nd query,
Initialisation is not the same as assignment , string object default constructor takes const char * to initialise . Assignment is a completely differenet story(if not,someone please do correct me ).
"" is a string literal of type const char[], and you are adding the string literal, i.e. the pointer to the first element, '\0', to another character. This will naturally give you something else then you expected.
If you want it to be the same as s += 'a', you'll need to use a std::string literal: s += ""s + 'a';. This works, as ""s is an empty std::string, and you just add another character to it.
When you write s="" + 'a'; Remember that "" is not a std::string but a const char*. And const char* doesn't have a predefined concatenation operator. That's why you are having an unexpected behavior instead of concatenation.
I have the following code to convert a string to char :
string tempLine = dataLine[studentIndex];
char str = tempLine.c_str();
but this line returns an error : " a value of type "constant char *" cannot be used to initialize an entity of type "char".
How can I fix this issue??
should be:
const char *str = tempLine.c_str();
Note that you're not supposed to change the content of the string. Generally, its not a good way to work with C++ strings. If you really have to fully convert a C++ string to C string - allocate memory and use strcpy to copy data, don't use the C++ string buffers directly.
edit for your request in the comments: Look here for C++ learning resources.
You cannot convert a const char*, which is what std::string::c_str() returns, to char. Change:
char str = tempLine.c_str();
to:
const char* str = tempLine.c_str();
Note this does not copy the characters in tempLine to str, str just refers to the characters in tempLine.
I'm getting back into c++ and have the hang of pointers and whatnot, however, I was hoping I could get some help understanding why this code segment gives a bus error.
char * str1 = "Hello World";
*str1 = '5';
ERROR: Bus error :(
And more generally, I am wondering how to change the value of a single character in a cstring. Because my understanding is that *str = '5' should change the value that str points to from 'H' to '5'. So if I were to print out str it would read: "5ello World".
In an attempt to understand I wrote this code snippet too, which works as expected;
char test2[] = "Hello World";
char *testpa2 = &test2[0];
*testpa2 = '5';
This gives the desired output. So then what is the difference between testpa2 and str1? Don't they both point to the start of a series of null-terminated characters?
When you say char *str = "Hello World"; you are making a pointer to a literal string which is not changeable. It should be required to assign the literal to a const char* instead, but for historical reasons this is not the case (oops).
When you say char str[] = "Hello World;" you are making an array which is initialized to (and sized by) a string known at compile time. This is OK to modify.
Not so simple. :-)
The first one creates a pointer to the given string literal, which is allowed to be placed in read-only memory.
The second one creates an array (on the stack, usually, and thus read-write) that is initialised to the contents of the given string literal.
In the first example you try to modify a string literal, this results in undefined behavior.
As per the language standard in 2.13.4.2
Whether all string literals are
distinct (that is, are stored in
nonoverlapping objects) is
implementation-defined. The effect of
attempting to modify a string literal
is undefined.
In your second example you used string-literal initialization, defined in 8.5.2.1
A char array (whether plain char,
signed char, or unsigned char) can be
initialized by a string- literal
(optionally enclosed in braces); a
wchar_t array can be initialized by a
wide string-literal (option- ally
enclosed in braces); successive
characters of the string-literal
initialize the members of the
array.
How do I append a string to a char?
strcat(TotalRam,str);
is what i got but it does not support strings
std::String has a function called c_str(), that gives you a constant pointer to the internal c string, you can use that with c functions. (but make a copy first)
Use + on strings:
std::string newstring = std::string(TotalRam) + str;
If you want it as a char[] instead, you need to allocated memory on the heap or stack first. After that, strcat or sprintf are possible options.
You can't append a string to a char, you can only append a string to a string (or a char* if using the C string functions). In your example, you'll have to copy (the char) TotalRam into a string of some sort, either a C++ std::string, or make a char[2] to hold it and the required terminating NULL character. Then you can either use the C++ string with C++ functions or the char[2] with strcat and friends.
for performance, do this:
char ministring[2] = {0,0};
// use ministring[0] as your char, fill it in however you like
strcat(ministring,str);
The char array is stack-allocated so it is extremely fast, and the second char with the value of zero acts as a string terminator so that functions like strcat will treat it as a 'c' string.