C ++“cin”只读取第一个字 [英] C++ "cin" only reads the first word

查看:425
本文介绍了C ++“cin”只读取第一个字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

我在Turbo C ++ 4.5中工作。代码运行正常,但它没有给出所需的输出
例如如果我给输入作为steve hawking只有steve正在显示。

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?

推荐答案

使用>> 流一次读取一个字。要将整行读取到 char 数组中:

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

cin.getline(str, sizeof str);

当然,一旦你学会了如何实现一个字符串,你应该使用 std :: string 并读为

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

getline(cin, str);

从这个世纪获得编译器也是一个好主意;你的15岁以上,C ++自那时以来发生了重大变化。 Visual Studio Express是一个不错的选择,如果你想要一个免费的Windows编译器;其他编译器可用。

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.

这篇关于C ++“cin”只读取第一个字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆