2014-03-05 124 views
1

輸入不是結束對輸入輸入在scanf不終止於C++

5 
1 10 
10 8 
8 2 
2 1 
1 10 

但對於其他輸入像

5 
1 1 
1 2 
1 3 
1 4 
1 5 

它工作正常。 我已經嘗試了各種方式,如通過使用條件來終止循環,但它不工作。

#include<utility> 
#include<iostream> 
#include<set> 
#include<cstdio> 
// where a==breadth b== index 
#define MP(a,b) make_pair(-a,b) 
#define INDEX it->second 
#define K1 a[INDEX][2] 
#define getL(i,k) a[(i)][0] 
#define getB(i,k) a[(i)+(k)-1][1] 
#define COST(a,b,c) ((a)*(b)*(c)) 
#define REMOVE(a,i) s.erase(s.find(MP(a,i))) 
#define PUSH(a,i) s.insert(MP(a,i)) 
#define FIND(a,i) s.find(MP(a,i)) 
using namespace std; 

set < pair < int , int > > s; 
set < pair < int , int > >::iterator it,p; 


#define MAX 1000 
int a[MAX][3]; 

int solve(int n){ 
    int i,idx,idx2,k1,k2,last=n-2; 
    int value=0; 
    a[n-1][2]=1; 
    for(i=0;i<n-1;i++) 
    { 
     a[i][2]=1; 
     s.insert(MP(a[i][1],i));//the value will be added on the basis of hte 
    } 
    cout << s.size(); 
    while(!s.empty()) 
    { 
     cout << "the minum"; 
     it=s.begin(); 
     idx=INDEX; 
     k1=K1; 
     idx2=idx+k1; 
     k2=a[idx2][2];//matrix with which the idx matrix has to be multiplied 

     s.erase(it); 
     cout << getB(idx2 ,k1); 
     cout << idx2; 
     value+=COST(getL(idx,k1),getB(idx,k1),getB(idx2,k2)); 
     a[idx][2]=k1+k2;// all the values will be update by now 
     a[idx2][2]=k1+k2; 
     if(idx==last)// if the index has to be equal to the last 
     {// multiply the matrix but don't put it in the tree 
      last=idx-a[(idx-1)][2];// 
     } 
     else 
     { 
      REMOVE(getB(idx2,k2),idx2); 
      PUSH(getB(idx2,k2),idx); 
     } 
    } 

    return value; 
} 


int main(){ 
    int n,i; 
    printf("Enter the number of matrix\n"); 
    scanf("%d",&n); 
    printf("Now Enter the dimensions of the matrix\n"); 
    // the output is not terminating in the loop 
    // 
    for(i=0;i<n;i++) 
    { 
     scanf("%d %d",&a[i][0],&a[i][1]); 
    } 
    cout << "Input terminated"; 

    printf("\nThe approx number of calculations required are %d",solve(n)); 

    return 0; 
} 
+2

你爲什麼不加入一些臨時的打印輸出的調試?你通過循環之前,通過打印N'的'價值的'i'每次值,'scanf'等的返回值 –

+0

請學會系統地縮進。它提高了獲得良好答案的機會。 –

+2

*總是*檢查任何'scanf'函數的返回值。它返回它多少項目解析,如果小於你提供什麼作爲參數,它的意思是「解析錯誤」,而*將離開未解析數據流中的*所以下次'scanf'將再次看到它,並再次失敗。 – hyde

回答

0

在cout中不使用endl可能會導致很多次問題。我不知道確切的原因,但是在使用printf或scanf之前,特別是在使用cout使用print語句時,我遇到了這種情況。