注册 登录
编程论坛 C++教室

getline在vc6.0中的一个小问题

yxb0001 发布于 2009-09-09 12:28, 881 次点击
下面小程序中为什么在vc++6.0中运行结果却得不到所需的结果?

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr);
  cout << "Hello " << mystr << ".\n";
  cout << "What is your favorite color? ";
  getline (cin, mystr);
  cout << "I like " << mystr << " too!\n";
  return 0;
}


在VC++6.0运行,其结果如下:(下面黑粗体字是键盘输入的)
What's your name? Aqua  
Hello Aqua.
What is your favorite color? blue
I like too!


为什么在所需结果"I like blue too!"中会缺少"blue"?
6 回复
#2
最左边那个2009-09-09 12:50
因为你下面这里:
 cout << "What's your name? ";
  getline (cin, mystr);

你输入名字以后,点回车,它还要你继续输入内容,这时候你继续输入的内容,就会被
 cout << "What is your favorite color? ";
  getline (cin, mystr);

这里的mystr读取

所以其实你
cout << "What is your favorite color? ";  
  getline (cin, mystr);
这里输入的内容,是第3行,是没有被读取的


#3
最左边那个2009-09-09 12:51
因为你下面这里:
 cout << "What's your name? ";
  getline (cin, mystr);

你输入名字以后,点回车,它还要你继续输入内容,这时候你继续输入的内容,就会被
 cout << "What is your favorite color? ";
  getline (cin, mystr);

这里的mystr读取

所以其实你
cout << "What is your favorite color? ";  
  getline (cin, mystr);
这里输入的内容,是第3行,是没有被读取的


#4
最左边那个2009-09-09 12:53
  cout << "What's your name? ";
  getline (cin, mystr);

这里会要求你写入2行,第一行被name读取,第二行被color读取
所以  
cout << "What is your favorite color? ";
 getline (cin, mystr);

这里输入的其实是第3行,没有被读取
#5
xufen3402009-09-09 14:24
准确说这是vc的一个漏洞,http://support.,改正方法上面也提到了,这个文件Microsoft Visual Studio\VC98\Include\STRING中。
#6
yxb00012009-09-09 22:30
谢谢。

第5楼从根本上解决了此问题。第4楼说明了在此小"bug"下如何操作才能得到结果。都是高手。
#7
yxb00012009-09-10 16:46
一般可采用cin.getline语句解决,如下:

#include<iostream.h>
 
int main()
{
    char mystr[100];
    cout<<"what's your name? ";
    cin.getline(mystr,100);
    cout<<"Hello "<<mystr<<".\n";
    cout<<"what is your favorite color? ";
    cin.getline(mystr,100);
    cout<<"I like "<<mystr<<" too!\n";
    return 0;
}
1