c++ char to const char* [duplicate] - c++

This question already has answers here:
C++ convert char to const char*
(5 answers)
Closed 10 years ago.
I need to convert a character in a character array to a const char * in order to print it to a file using fstream. I'm not sure exactly how to do so. I've tried putting the single char into a string, then using c_str(), but that does not work..

If you want to write a single character, just use operator<<:
char arr[256] = "...";
fstream f(...);
f << arr[2];
You don't need to convert the character to a C string.

Hm... If you have a character array, that already decays into char * when passed to a function.
If you need only one character:
char array[128]; // whatever - you want to extract the char from this
char s[] = { array[64], 0 };
then use s which now can decay into char *.
Edit: D'oh, I just read this:
in order to print it to a file using fstream
Well, then don't bother converting it to a proper C string. operator<< knows its job, and it's overloaded for char too.

Related

why char * works with const only [duplicate]

This question already has answers here:
What is the type of string literals in C and C++?
(4 answers)
Closed 6 months ago.
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define nline "\n"
int main(){
//const char *p="hello world";
// court<<p;
char *p="hello world";
cout<<p;
}
C:\Users\Dell\AppData\Roaming\Sublime Text\Packages\User\cses2.cpp: In function 'int main()':
C:\Users\Dell\AppData\Roaming\Sublime Text\Packages\User\cses2.cpp:7:10: warning: ISO C++ forbids converting a string constant to 'char' [-Wwrite-strings]*
char *p="hello world";
^~~~~~~~~~~~~
"hello world" is a const char[12]. A c-array of 12 constant (!) characters (note that one is for the null terminator).
In early C++ standards it was allowed to get a char * to a string literal due to compatibility with C. Though, it was nevertheless forbidden to actually modify the characters of the string literal via the char *.
This changed in C++11 and since then string literals have proper const correctness.
If you do want a string that can be modified, then use a std::string. Note that the pointer you obtain from the literal is not a string, its just a pointer to a (non-modifiable) c-string. If you want a string rather than a pointer to one, you need to use a string.

understand how char works in c++ [duplicate]

This question already has answers here:
What happened when we do not include '\0' at the end of string in C?
(5 answers)
What is the difference between char s[] and char *s?
(14 answers)
Why do string literals (char*) in C++ have to be constants?
(2 answers)
Closed last year.
I am a C++ newbie. Although many similar questions have been asked and answered, I still find these concepts confusing.
I know
char c='a' // declare a single char c and assign value 'a' to it
char * str = "Test"; // declare a char pointer and pointing content str,
// thus the content can't be modified via point str
char str1[] = "Test"; // declare a char array str1 and assign "Test" to it
// thus str1 owns the data and can modify it
my first question is char * str creates a pointer, how does char * str = "Test"; work? assign a string literal to a pointer? It doesn't make sense to me although it is perfectly legal, I think we can only assign an address to a pointer, however "Test" is a string literal not an address.
Second question is how come the following code prints out "Test" twice in a row?
char str2[] = {'T','e','s','t'}; // is this line legal?
// intializing a char array with initilizer list, seems to be okay to me
cout<<str2<<endl; // prints out "TestTest"
why cout<<str2<<endl; prints out "TestTest"?
char * str = "Test"; is not allowed in C++. A string literal can only be pointed to by a pointer to const. You would need const char * str = "Test";.
If your compiler accepts char * str = "Test"; it is likely outdated. This conversion has not been allowed since C++11 (which came out over 10 years ago).
how does char * str = "Test"; work?
String literals are implicitly convertible to a pointer to the start of the literal. In C++ arrays are implicitly convertible to pointer to their first element. For example int x[10] is implicitly convertible to int*, the conversion results in &(x[0]). This applies to string literals, their type is a const array of characters (const char[]).
how come the following code prints out "Test" twice in a row?
In C++ most features related to character strings assume the string is null terminated, which is implied in string literals. You would need {'T','e','s','t','\0'} to be equivalent to "Test".

Can someone please explain this output? [duplicate]

This question already has answers here:
Why in the code "456"+1, output is "56" [duplicate]
(3 answers)
What is the answer when integer added to string constant in C language?
(4 answers)
Closed last year.
cout<<"ccccc"+2;
Output:
ccc
I tried searching for it online and I know it is a very dumb question but couldn't find anything anywhere. Please if someone could help me out.
"ccccc"+2;
"ccccc" decays to the const char * pointer referencing the first character of the string literal "ccccc". When you add 2 to it, the result references the third element of the string literal.
It is the same as:
const char *cptr = "ccccc";
cptr += 2;
cout << cptr;
When you wrote:
cout<<"ccccc"+2;
The following things happen(to note here):
"ccccc" is a string literal. In particular, it is of type const char[6].
Now, this string literal decays to a pointer to const char which is nothing but const char* due to type decay. Note that the decayed const char* that we have now is pointing to the first character of the string literal.
Next, 2 is added to that decayed pointer's value. This means that now, after adding 2, the const char* is pointing to the third character of the string literal.
The suitable overloaded operator<< is called using this const char*. And since this const char* is pointing to the third character of the string literal, you get the output you observe.

Generating a char using input from user in C++ [duplicate]

This question already has answers here:
How to convert a std::string to const char* or char*
(11 answers)
Closed 7 years ago.
I wish to make a char with digits between 0-9. The user decides how many digits to use.
For example, if the user inputs 4, the char should be 01234.
Please note I cannot use the string data type. I have to use char.
I know how to generate a string for the same logic but not a char.
So if there is a way to convert string to char, that will work well. I tried
string randomString; //this contains the set of numbers 0-9 on the basis of the users input
char charString = randomString;
This however does not work.
So if there is a way to convert string to char
Yes, it's called a character array and you can easily convert a string type to a character array like so:
const char* charString = randomString.c_str();
You can find more information about c_str() method here and you should review this material regarding character arrays.
If you require a non-const (can be modified) character array, refer to the above links which will explain it and actually give examples about how to accomplish that.

difference between char array and string in cplusplus [duplicate]

This question already has answers here:
What is the difference between a Character Array and a String?
(10 answers)
Closed 9 years ago.
I want to know the difference between character array and string in c++.
Can any one answer to this??
Please,
Thanks
Vishnukumar
string is a class/object, with methods and encapsulated data.
A char array is simply a contiguous block of memory meant to hold chars.
(1) char array is just a block of char type data:
e.g. char c[100]; // 100 continuous bytes are allotted to c
(2a) By string, if you mean char string then, it's little similar to array but it's allocated in the readonly segment of the memory and should be assigned to a const char*:
e.g. const char *p = "hello"; // "hello" resides in continuous character buffer
[note: char c[] = "hello"; belongs to category (1) and not to (2a)]
(2b) By string if yo umean std::string then, it's a standard library class from header and you may want to refer its documentation or search on web