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?

  • What is received is what? str or n ? - Harry

3 answers 3

 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); 
  • I need to know what the user enters. That is, if he enters a space - I have to issue an inscription saying that they should not do that. And cin reads only up to the space - IWProgrammer
  • one
    Check for a start ... - Harry

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.

  • The way Harry does exactly what is requested - converts an array into a string. The one that the author gave Where he puts the completion - there will be :) In general, let's start with the fact that the author reads in a completely different array, in n , not in str ... - Harry
  • It is easier to solve this problem at the initialization stage: char str[1000] = {}; . Well, checking for the number of characters entered is also necessary, but this is to the author of the question. - ixSci

Can do so

 #include <iostream> #include <string> int main(){ char buf[] = "Hello, World!"; std::string str; str = buf; std::cout << str << std::endl; return 0; }