#include class String { char str[100]; public: void input() { cout<<"Enter string...">

C ++ "cin" only reads the first word

#include<iostream.h> #include<conio.h> class String { char str[100]; public: void input() { cout<<"Enter string :"; cin>>str; } void display() { cout<<str; } }; int main() { String s; s.input(); s.display(); return 0; } 

I work in Turbo C ++ 4.5. The code works fine, but does not give the desired result, for example, if I give input as "steve hawking", only "steve" is displayed. Can anybody help?

+5
source share
5 answers

Using >> in a stream reads one word at a time. To read an entire string into a char array:

 cin.getline(str, sizeof str); 

Of course, once you learn how to implement a string, you should use std::string and read it as

 getline(cin, str); 

It would be nice to get a compiler from this century; You are over 15 years old, and C ++ has changed significantly since then. Visual Studio Express is a good choice if you need a free compiler for Windows; other compilers are available.

+22
source
 cin>>str; 

This is just a read in the next token. In C ++ iostreams tokens are separated by spaces, so you get the first word.

You probably want a getline that reads a whole line in a line:

 getline(cin, str); 
+3
source

You can use:

  cin.read( str, sizeof(str) ); 

But it will fill the buffer. You should use cin.getLine () instead, as suggested by MikeSeymour

+2
source

You can use cin.getline to read the entire line.

+1
source

use this

 cin.getline(cin, str); 
0
source

Source: https://habr.com/ru/post/1398652/


All Articles