C++ string库 getline问题
#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)
/* 倒着写 */
if(str0[a - 1] == str[b - 1])
{
count[a*b -1] = 1;
}
cout<<"for test 4.6"<<endl;
for(int m = a-2; m >= 0; m--)
{
count[b*m + b - 1] = count[b*(m+1) + b - 1];
if(str0[m] == str[b - 1])
count[b*m + b - 1]++;
}
cout<<"for test 5"<<endl;
for(int n = b-2; n >= 0; n--)
{
for(int m = a-2; m >= 0; m--)
{
count[b*m + n] = count[b*(m+1) + n];
if(str0[m] == str[n])
{
count[b*m + n] += count[b*(m+1) + (n+1)];
count[b*m + n] %= 10000;
}
}
}
/*
for(int i = 0; i < a; i++)
{
for(int j = 0; j < b; j++)
cout<<count[i*b+j];
cout<<endl;
}
*/
// cout<<"for test 6"<<endl;
cout<<"Case #"<<time+1<<": "<<count[0]%10000<<endl;
delete[] count;
}
return 0;
}
这里先有cin>>times;
后有getline(cin,str0);
这样子,输入总是不正确。
比如。我一输入3. 总是报错
如果没有cin>>times;
程序就不报错
解决之道
语句cin>>times;执行时 当你输入times的值以后 会有一个回车
而getline(cin,str0); 是将 回车前面的输入存储到str0中 此时为空
你可以这样
在cin>>times;后面声明一个char型变量
char c;
c=getchar()();//用来接收这个回车
if(c == '\n')
{
getline(cin,str0);
}