C++ "cin" 只读取第一个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9469264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:52:23  来源:igfitidea点击:

C++ "cin" only reads the first word

c++string

提问by rick

#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?

我正在使用 Turbo C++ 4.5。代码运行良好,但它没有给出所需的输出,例如,如果我将输入作为“steve hawking”,则只显示“steve”。有人可以帮忙吗?

回答by Mike Seymour

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

>>在流上使用一次读取一个单词。要将整行读入char数组:

cin.getline(str, sizeof str);

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

当然,一旦你学会了如何实现一个字符串,你应该像这样使用std::string和阅读它

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.

获得本世纪的编译器也是一个很好的主意;你已经超过 15 岁了,从那时起 C++ 发生了重大变化。如果您想要一个免费的 Windows 编译器,Visual Studio Express 是一个不错的选择;其他编译器可用。

回答by Brendan Long

cin>>str;

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

这只会读入下一个令牌。在 C++ iostreams 中,标记由空格分隔,因此您会得到第一个单词。

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

您可能需要getline,它将整行读入一个字符串:

getline(cin, str);

回答by roymustang86

You can use :

您可以使用 :

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

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

但是,这将填满缓冲区。相反,您应该像 MikeSeymour 建议的那样使用 cin.getLine()

回答by Qian

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

您可以使用 cin.getline 阅读整行。

回答by Stijn

use this

用这个

cin.getline(cin, str);