C++ 中 关于getline函数的疑惑

来源:百度知道 编辑:UC知道 时间:2024/06/30 13:37:54
下面这段代码运行后,输入3,表示动态的定义了可以包含3个元素
(string类型)的数组
但是,分别输入完元素的值后,我想要程序显示第一个元素的值,可是
第一个元素总是空值,不知道哪里出了错误,哪位高手指点一下....多谢

#include <iostream>
#include <string>
#include <cstddef>

using namespace std;

int main()
{
char wait; //运行到最后时停止,以便观察结果

string line;
string *values;
size_t d=0;
cout<<"Please enter the demision :"<<endl;
cin>>d;
values=new string[d];
cout<<"\nPlease enter "<<d<<" values! :"<<endl;
for(size_t times=0; times<d; times++)
{
getline(cin,line);
values[times]=line;
}

cout<<"\nThe first you entered is :";
cout<<" "<<values[0]<<endl;

delete [] values;

cin>>wait; /

可能是输完数字后按了回车,导致回车的第2个字符被getline读走了.你可以在
for前面加cin.ignore(1024,'\n');清空缓冲区试试.不过由此会产生在输入完3个字符串后,要多按一次回车才会输出的小BUG.

values[times]=line?不能这么赋值。用字符串拷贝函数strcopy

在cin>>d;后加个getchar();试试