C++ string库 getline问题

来源:百度知道 编辑:UC知道 时间:2024/06/14 21:32:14
请大家看看下面这段代码

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

int main()
{
cout<<"for test 1"<<endl;
int times = 0;
cin>>times;
cout<<"times = "<<times<<endl;
cout<<"for test 2"<<endl;
string str,str0;
str = "welcome to code jam";
int b = str.length();//短串
int* count;
cout<<"for test 3"<<endl;

for(int time = 0; time < times; time++)
{
getline(cin,str0);//读取一行,碰到空格不停。
cout<<"str0 = "<<str0<<endl;
int a = str0.length();//长串
count = new int[a*b];
cout<<"for test 4"<<endl;

/* 归零 */
for(int i = 0; i < a*b; i++)
count[i] = 0;
cout<<"for test 4.5"<<endl;

//(a,b) (m,n)
/* 倒着写 */

语句cin>>times;执行时 当你输入times的值以后 会有一个回车
而getline(cin,str0); 是将 回车前面的输入存储到str0中 此时为空
你可以这样
在cin>>times;后面声明一个char型变量
char c;
c=getchar();//用来接收这个回车
if(c == '\n')
{
getline(cin,str0);
}

请直接使用MFC,那个简单

getline之前加个getchar()