c++中getline函数

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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值