2013-05-20 80 views
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

1.使用'std :: getline'。 2. http://stackoverflow.com/search?q=%5Bc%2B%2B%5D%20getline%20skipping – chris

+0

你可以發佈你當前獲得的輸出以及你期望的結果嗎? (和你的輸入) –

+1

'char numb [MAX];'後面跟着一個unchecked'getline(cin,numb);'是一個緩衝區溢出等待發生。最好使用'std :: string's。 –

回答

1

我想你的輸入可能看起來像

something 
3 1 2 3 
some other thing 
4 1 2 3 4 

你第一次閱讀getline() 「東西」。然後你的算法讀取3作爲numbers,然後是三個數字。在這裏閱讀停止。下次您撥打getline()時,它會繼續讀取,直到達到第一個'\n'字符。所以當你想要時它不會讀「其他的東西」。

現在我不能嘗試它,但我認爲它可以在填充div陣列的循環之後使用額外的「啞」getline()正常工作。

相關問題