C++ cin 问题。不捕获用户的输入
我有以下方法,它不会捕获用户的任何内容。如果我输入新乐队作为艺术家姓名,它只会捕获“新”而忽略“乐队”。如果我使用 cin.getline() 而不是捕获任何内容。有什么想法如何解决这个问题吗?
char* artist = new char [256];
char * getArtist()
{
cout << "Enter Artist of CD: " << endl;
cin >> artist;
cin.ignore(1000, '\n');
cout << "artist is " << artist << endl;
return artist;
}
这效果很好。谢谢罗杰
std::string getArtist()
{
cout << "Enter Artist of CD: " << endl;
while(true){
if ( getline(cin, artist)){
}
cout << "artist is " << artist << '\n';
}
return artist;
}
I have the following method which is not capturing anything from the user.If I input New Band for the artist name, it only captures "New" and it lefts out "Band". If I use cin.getline() instead nothing is captured. Any ideas how to fix this?
char* artist = new char [256];
char * getArtist()
{
cout << "Enter Artist of CD: " << endl;
cin >> artist;
cin.ignore(1000, '\n');
cout << "artist is " << artist << endl;
return artist;
}
This worked just fine. Thank you Roger
std::string getArtist()
{
cout << "Enter Artist of CD: " << endl;
while(true){
if ( getline(cin, artist)){
}
cout << "artist is " << artist << '\n';
}
return artist;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
整个事情是一个普遍的改进,但使用 getline 可能对你的问题来说是最重要的。
The whole thing is a general improvement, but the use of getline is possibly the most significant for your question.
这是指定的行为;
istream
只能读取到一个空格或换行符。如果您想要整行,您可以使用getline
方法,正如您已经发现的那样。另外,请在任何新的 C++ 代码中使用
std::string
而不是char*
,除非有充分的理由。在这种情况下,它将帮助您避免缓冲区溢出等各种问题,而无需您付出任何额外的努力。This is the specified behaviour;
istream
s only read up to a space or a newline. If you want an entire line, you use thegetline
method, as you already discovered.Also, please use
std::string
instead ofchar*
in any new C++ code, unless there are very good reasons otherwise. In this case, it will save you from all kinds of problems like buffer overflows, without any extra effort on your part.如果您要在输入中包含空格分隔符,则需要使用 getline 供您输入。这会让你的忽略变得不必要。
If you're going to have white space separators in your input, you need to use getline for your input. That would make your ignore unnecessary.