How to convert a char array to a string in C ++? Suppose given:
char str[1000]; int i = 0; n[i] = getchar(); while (n[i] != '\n') { i++; n[i] = getchar(); } How is the resulting array converted to a string?
How to convert a char array to a string in C ++? Suppose given:
char str[1000]; int i = 0; n[i] = getchar(); while (n[i] != '\n') { i++; n[i] = getchar(); } How is the resulting array converted to a string?
string s = str; And that's all.
But it's much easier not to write all this, but to write
string s; getline(cin,s); The effect is the same :)
By the way, in the very first case I would just write, if you really want to work through an array:
char str[1000] = { 0 }; fgets(str,1000,stdin); Since in this case the array was not previously nullified, there are two ways
string s(str, i); either explicitly add a zero and then do an assignment
i++; str[i] = '\0'; string s(str); The method proposed by Harry has a bug :) it can add garbage characters to the end of the line at best.
n , not in str ... - Harrychar str[1000] = {}; . Well, checking for the number of characters entered is also necessary, but this is to the author of the question. - ixSciCan do so
#include <iostream> #include <string> int main(){ char buf[] = "Hello, World!"; std::string str; str = buf; std::cout << str << std::endl; return 0; } Source: https://ru.stackoverflow.com/questions/599324/
All Articles
strorn? - Harry