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
C++ "cin" only reads the first word
提问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 char
array:
>>
在流上使用一次读取一个单词。要将整行读入char
数组:
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
当然,一旦你学会了如何实现一个字符串,你应该像这样使用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
回答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);