6
#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 am working in Turbo C++ 4.5. The code is running fine but its not giving the desired output for e.g if i give input as "steve hawking" only "steve" is being displayed. Can anyone please help?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
rick
  • 913
  • 6
  • 13
  • 28

5 Answers5

25

Using >> on a stream reads one word at a time. To read a whole line into a char array:

cin.getline(str, sizeof str);

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

getline(cin, str);

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

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
4
cin>>str;

This only reads in the next token. In C++ iostreams, tokens are separated by whitespace, so you get the first word.

You probably want getline, which reads an entire line into a string:

getline(cin, str);
Brendan Long
  • 53,280
  • 21
  • 146
  • 188
2

You can use :

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

But, this will fill up the buffer. Instead you should use cin.getLine() as MikeSeymour suggested

roymustang86
  • 8,054
  • 22
  • 70
  • 101
1

You could use cin.getline to read the whole line.

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
Qian
  • 1,007
  • 7
  • 6
0

use this

cin.getline(cin, str);
animuson
  • 53,861
  • 28
  • 137
  • 147
Stijn
  • 285
  • 8
  • 22