convert a char* to std::string
I need to use an std::string to store data retrieved by fgets() . To do this I need to convert the char* return value from fgets() into an std::string to store in an array. How can this be done?
11 Answers 11
std::string has a constructor for this:
Note that this construct deep copies the character list at s and s should not be nullptr , or else behavior is undefined.
If you already know size of the char*, use this instead
This doesn’t use strlen.
EDIT: If string variable already exists, use assign():
Most answers talks about constructing std::string .
If already constructed, just use assignment operator.
I need to use std::string to store data retrieved by fgets().
Why using fgets() when you are programming C++? Why not std::getline() ?
Pass it in through the constructor:
You can use the function string.c_str() to go the other way:
I would like to mention a new method which uses the user defined literal s . This isn’t new, but it will be more common because it was added in the C++14 Standard Library.
Largely superfluous in the general case:
But it allows you to use auto, also with wide strings:
And here is where it really shines:
I’ve just been struggling with MSVC2005 to use the std::string(char*) constructor just like the top-rated answer. As I see this variant listed as #4 on always-trusted http://en.cppreference.com/w/cpp/string/basic_string/basic_string , I figure even an old compiler offers this.
It has taken me so long to realize that this constructor absolute refuses to match with (unsigned char*) as an argument ! I got these incomprehensible error messages about failure to match with std::string argument type, which was definitely not what I was aiming for. Just casting the argument with std::string((char*)ucharPtr) solved my problem. duh !
Not sure why no one besides Erik mentioned this, but according to this page, the assignment operator works just fine. No need to use a constructor, .assign(), or .append().
Convert Char to String in C
How do I convert a character to a string in C. I’m currently using c = fgetc(fp) which returns a character. But I need a string to be used in strcpy
9 Answers 9
To answer the question without reading too much else into it i would
You could use the second line in a loop with what ever other string operations you want to keep using char’s as strings.
Using fgetc(fp) only to be able to call strcpy(buffer,c); doesn’t seem right.
You could simply build this buffer on your own:
Note that this relies on the fact that you will read less than MAX_SIZE_OF_MY_BUFFER characters
You could do many of the given answers, but if you just want to do it to be able to use it with strcpy , then you could do the following:
The (char[2]) < (char) c, '\0' >part will temporarily generate null-terminated string out of a character c .
This way you could avoid creating new variables for something that you already have in your hands, provided that you’ll only need that single-character string just once.
A code like that should work:
I use this to convert char to string (an example) :
This is an old question, but I’d say none of the answers really fits the OP’s question. All he wanted/needed to do is this:
The relevant aspect here is the fact, that the second argument of strcpy() doesn’t need to be a char array / c-string. In fact, none of the arguments is a char or char array at all. They are both char pointers:
dest : A non-const char pointer Its value has to be the memory address of an element of a writable char array (with at least one more element after that). src : A const char pointer Its value can be the address of a single char, or of an element in a char array. That array must contain the special character \0 within its remaining elements (starting with src ), to mark the end of the c-string that should be copied.
How to cast char to string in C?
Im new to C and i encounter a problem with using strcat(). I looked up strcat and noticed that it takes string as arguments but when i split items from a char array is a char and when i use it as a argument for strcat it prints out error.
the purpose of the code is to split a string into two string that each contain all the characters in odd position or even position.However, when im tring to dereference the char pointer all i get is a Char but it seems i need string
4 Answers 4
Use a temporary string in strcat instead of strcat(out[0],*pa); .
Also, make sure that you allocate enough memory for out .
strcat() requires a pointer to a null-terminated string. You are dereferencing a pointer (with the * operator) which gives a char. You cannot simply cast a char to a pointer to sting. You might want to be using memcpy() instead of strcat(), but for copying single bytes a simple assignment using * operators on both the left and right sides would be fine. But as others have pointed out your code isn’t allocating space for you to copy the chars into, so you’re going to need to make additional changes to fix that. Also, you’ll have to remember to copy a final null byte to the end of both your output strings.
In C, a «string» is really just a pointer to a character; the string runs from that character to the terminating 0 byte (the NUL ).
If you dereference a string pointer, you get the character at that position. If the pointer is pointing to the start of the string, you get the first character of the string.
Your program has some problems. For one, you need to allocate space for the new strings. strcat() will try to copy characters wherever you tell it to, but it’s your job to make sure that there is room there and that it’s okay to write there. The declaration of out just declares two pointers, and initializes them to point to a zero-length constant string. Instead, you need to allocate storage, something like:
This makes two output buffers of 64 characters each, then sets up out with pointers to them.
Another problem: you declared a length of 10 for your char array, but then you initialize it with a length-10 string. This means there is no room for a terminating NUL byte and C won’t put one. Then strcpy() or strcat() will copy extra garbage from the string, until there happens to be a NUL byte. If you are lucky there will be one right away and you won’t spot the error, but if you aren’t lucky you will get weird garbage.
Just let the compiler count how many bytes in your string and do the right thing. Leave out the length:
convert char to string in c++
I am trying to reduce a string by giving it to a function. For example: If i have «abrakadabra«, the function shall return a string of «abrkd«. Which means that all characters should exist only once in the return value. I have the following function:
I know that ‘text.at(i)’ gives a char back. But I want to convert this character to a string so I can concatenate it.
7 Answers 7
Use push_back method to append single char to a std::string . You can also use operator += to do that.
I propose yet another approach:
C++ comes with a lot of container logic.
You can convert your string to a set , which allows only one element of each value:
Downside of this is that the letters are sorted afterwards, and not in the order of first appearance in the string, but you didn’t specify whether you needed a specific order.
You can convert the set back to a string using the range constructor, too:
That is typically done with a std::stringstream :
Just to answer the titular question, while as others have noted, is not actually useful for this problem:
There’s a std::string constructor which takes a character and a repeat count. So to create a string consisting of a single character, you can use a repeat count of 1:
But this is quite wasteful, even on implementations with a small-string optimization. So simply append your character directly to your existing string as Andrew suggests in his answer.
Char to string
есть массив char. есть строка string. как присвоить значению string-a значение char-a?
есть массив char. есть строка string. как присвоить значению string-a значение char-a?
Строка: чем отличается строки string, char, char*?
Помогите разобраться,совсем плохо идёт,чем отличается строки string,char,char* И если можно пару.
Как преобразовать char* в string и вывести переменную string на экран?
for (int k = 0; k 2
Решение
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь.
Где и почему используют ту или иную строку std::string, char[], System::String^ ?
Где и почему используют ту или иную строку std::string, char, System::String^ ? Объясните.
String, AnsiString или char * ? Что лучше использовать с классами? И как работать с типом string
Добрый вечер. Мне нужно в одну строку str1 поместить строку str2. Обе они типа string. В интернете.
char char* string и константные значения
Робот может перемещаться в 4 направлениях c-Север, u- Юг, z- Запад, v- Восток ипринемать 3 цифровые.