c++ 中getline()的用法

来源:百度知道 编辑:UC知道 时间:2024/05/17 03:59:44
我用vc++6.0不行,后来换了vs2005也不行,我用了
string addr;
getline(cin,addr);
都没有输入的机会,执行到输入那里就直接跳过了…
源程序在http://user.qzone.qq.com/305335291/blog/1240376037这里

这样用是对的,这个不知道你程序的上下文 没法说阿
因为你之前cin后缓冲区中有一个'\n'字符,所以getline直接就结束了,你可以在cin后加上getchar();这样就行了

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
string addr="";

getline(cin,addr);
cout<<addr;
system("PAUSE");
return EXIT_SUCCESS;
}

一切正常

原因可能是你之前的程序已经使用了cin

当输入age后,缓冲区中有'\n'字符,当调用getline时,发现'\n',立即结束
,所以在getline之前,应该刷新缓冲区或调用getchar()函数从缓冲区中读出'\n'
void get_value1()
{
cout<<"input age:";
cin>>age;
cout<<"input address:";
cin.sync();//刷新缓冲区
getline(cin,addr);

}