It is necessary to read a string from the console into the char array.

The problem is that scanf and cin read the string only up to the first space, and I need to write the entire string to the array.

How do I solve this problem?

  • Probably cin , not cout . - maestro
  • There are plenty of examples, type - c ++ cin - and here it is happiness. - 0xdb

1 answer 1

Use the member function of the getline input stream class.

Here are their ads

 basic_istream<charT,traits>& getline(char_type* s, streamsize n); basic_istream<charT,traits>& getline(char_type* s, streamsize n, char_type delim); 

Or you can use the member function of the get class in the input stream. Her ad looks like the previous function.

 basic_istream<charT,traits>& get(char_type* s, streamsize n); basic_istream<charT,traits>& get(char_type* s, streamsize n, char_type delim); 

The difference between these functions is that the first function reads the chimvol delim (if it is not specified, the newline character) from the input stream, but does not add it to the string. While the second function leaves this character in the input stream.

I think you better use the first function.

Here is an example of working with the getline function.

 #include <iostream> int main() { const size_t N = 50; char s[N]; std::cout << "Enter a sentence: "; std::cin.getline( s, N ); std::cout << '\n' << s << std::endl; return 0; } 

The dialogue with this function may look, for example, as follows:

 Enter a sentence: Hello World! Hello World! 

If you entered with the operator operator >> before calling this function, then a newline character may remain in the input buffer. It can be removed by calling another member function of the ignore class. The simplest call to this function looks like

 std::cin.ignore(); 

Either to remove a newline character, then

 #include <limits> //... std::cin.ignore( std::numeric_limits<streamsize>::max() ); 
  • I use this way: 'cin.getline (dirDirectory, 255);' the program does not wait until I enter the value, but continues its work as if the getline method and no. dirDirectory is 0 - Rikipm
  • @Rikipm Before calling this function, at least std :: cin.ignore () is called; to remove the newline character that remained in the buffer most likely after calling operator >>. - Vlad from Moscow
  • Thanks for the help in solving this problem - Rikipm