0
在此代碼中,getline不適用於i = 1,但對於i = 0,它工作得很好。 我應該怎麼做才能重複使用getline函數。這段代碼需要一個數字並檢查它的可分性。「numb」用於存儲數字。對於i = 0,所有的計算都很好,但是當它用於第二個轉,不知道發生了什麼,但cin.getline不起作用。cin.getline()在第二次調用時不起作用
#include <iostream>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#define MAX 1050
using namespace std ;
int call_div (char *num ,long div)
{
int len =strlen (num) ;
int now ;
long extra ;
for (now = 0,extra=0; now < len; now += 1)
{
extra = extra *10 + (num [now] -'0') ;
extra = extra %div ;
}
return extra ;
}
int main (int argc, char const* argv[])
{
int testcase,numbers ,flag =0;
char numb[MAX] ;
cin >> testcase ;
getchar() ;
for (int i = 0; i < testcase; i += 1)
{
cout << i << endl ;
int div[14] ;
cin.getline(numb) ; // i= 0 ,it works fine ,i=1 ,it doesn't work
cin >> numbers ;
for (int j = 0; j < numbers; j += 1)
{
cin >> div[j] ;
}
for (int k = 0; k < numbers; k += 1)
{
// cout << div[k]<< ' ' << call_div (numb,div[k]) << endl ;
if (call_div (numb,div[k])==0)
{
flag = 1 ;
}
else {
flag = 0 ;
break;
}
}
if (flag==0)
{
cout << "simple"<< endl ;
}
else
cout << "wonderful" << endl ;
}
return 0;
}
1.使用'std :: getline'。 2. http://stackoverflow.com/search?q=%5Bc%2B%2B%5D%20getline%20skipping – chris
你可以發佈你當前獲得的輸出以及你期望的結果嗎? (和你的輸入) –
'char numb [MAX];'後面跟着一個unchecked'getline(cin,numb);'是一個緩衝區溢出等待發生。最好使用'std :: string's。 –