2015-03-08 64 views
-1

所以我仍然在研究可以做代數方程式的計算器,但我遇到了一點障礙。我想將程序設置爲如果輸入超過4個不同數字的地方,它會在屏幕上打印一條通知&讓您有第二次機會做到這一點。但是,我的forloop不起作用。如果輸入了5個字符,它會詢問你想要做什麼類型(類型的含義是否需要4個正數4個負數等),然後重置程序。下面的代碼是什麼樣子(如果有更多的信息需要,我會更新線程的要求):如何使用forloop來確定已輸入的數字字符?

else if (type == "foil") 
{ 
    cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n"; 
    cin >> X1 >> X2 >> Y1 >> Y2; 
    int nCount = 0; 
    for (nCount == cin.beg; nCount != cin.end; nCount++) 
    { 
     if (nCount > 4) 
     { 
      printf("Please input 4 diffent numbers.\n"); 
      Sleep(1000); 
      return main(); 
     } 
     else 
     { 
      break; 
     } 
    } 
//after forloop is when you're given a chance to input the different   
//combinations foil can have, 2 negative 2 positive, 4 negative, 4 positive, etc. 
} 
+0

我認爲有*少*需要的信息。你應該刪除與該問題無關的所有內容,例如while(1)'loop,所有'std :: cout'輸出,'Sleep'調用,toupper','_getche'等等。 .. – 2015-03-08 19:00:21

+0

啊,好吧,對不起,只是想確保我沒有錯過任何東西。我會繼續編輯這些東西。 – Jmd82 2015-03-08 19:01:29

+0

問題是這個問題不應該包含任何多餘的額外東西,也不應該太短以至於不能真正展現問題。請參閱http://sscce.org/。 – 2015-03-08 19:05:42

回答

0

好吧,我想有幾件事情要你的問題。 首先你會在第一次迭代中斷開循環,因爲你的if語句將總是使用else分支。 在進入for循環時,語句nCount > 4將始終爲假。

第二個問題是nCount == cin.beg; nCount != cin.end; nCount++ 我猜想提取操作符從流中刪除字節,找不到任何參考atm。所以你無法確定它的大小。

我會推薦做這樣的事情來驗證用戶輸入。

char accepted = 'n'; 
do { 
    accepted = 'n' 
    cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n"; 
    cin >> X1 >> X2 >> Y1 >> Y2; 
    cin.clear(); 

    //Print out values 
    cout << "Are those values corrent? y/n" 
    cin >> accepted; 
    cin.clear(); 
} while (accepted != 'y'); 
0

我建議你使用一個std::vector牽你的變量:

std::vector<int> values(4); 
cout << "Please input the value of X1, X2, Y1, and Y2 (Example: 8 9 4 9)\n"; 
for (unsigned int i = 0; 
    (cin.good()) && (i < 4); 
    ++i) 
{ 
    cin >> values[i]; 
} 
if (values.size() < 4) 
{ 
    // handle error 
} 

通過您的變量的命名慣例,如果您打包值PointsCoordinatespair是你的程序會更好。

struct Coordinate 
{ 
    int x; 
    int y; 
    friend istream& operator>>(istream& inp, Coordinate& p); 
}; 

istream& operator>>(istream& inp, Coordinate& p) 
{ 
    inp >> p.x >> p.y; 
    return inp; 
} 

int main(void) 
{ 
    Coordinate p1; 
    Coordinate p2; 
    cout << "Please input point 1:"; 
    if (!(cin >> p1)) 
    { 
    cerr << "Error inputting point 1.\n"; 
    return EXIT_FAILURE; 
    } 
    cout << "\nPlease input point 2:"; 
    if (!(cin >> p2)) 
    { 
    cerr << "Error inputting point 2.\n"; 
    return EXIT_FAILURE; 
    } 
    // ... 
    return EXIT_SUCCESS; 
} 
+0

好的答案,但這樣做會要求整個程序被重寫爲正確的?特別是箔的程序部分,因爲它輸出這個(和它的不同變化): \t \t \t cout <<「回答:」<<「 - 」<<(X1 * Y1)<<「x」 <<「 - 」<<(X1 * Y2)<<「y」<<「 - 」<<(X2 * Y1)<<「x」<<「 - 」<<(X2 * Y2)<<「y 「<<」\ n「; – Jmd82 2015-03-09 00:07:25

相關問題