2014-10-29 51 views
-2

我試圖在C++中製作自動售貨機。我只是試圖添加一些驗證,所以它不會中斷。我首先要求用戶輸入他們選擇的前兩個字母。我知道我不能阻止他們進入更多的一個字符。我創建了一個do while循環來確保第一個字符和第二個字符不會比maxChar大。我沒有得到任何語法錯誤,但我沒有得到正確的答案。我知道一個字符不同於int,但是如何將char轉換爲int?任何幫助將不勝感激在C++中添加兩個單個字符

#include <cstdlib> 
#include <iostream> 
#include <iomanip> 
#include <string> 
#include <sstream> 
#include <set> 
#include <cctype> 
#include <locale> 


const int maxChr = 3; 
char chrOne,chrTwo; 
    do 
    { 
     cin >>chrOne>>chrTwo; 
     if(chrOne + chrTwo > maxChr) 
     { 
      cout <<"you have too many characters" 
      "please try again" << endl; 
     } 
     while (chrOne + chrTwo > maxChr); 

    } 
+6

所以......''A'+'B'肯定會比3大。 – crashmstr 2014-10-29 16:24:29

+0

您是否總結了字符的**值**以確定**有多少**由用戶輸入? – 2014-10-29 16:25:30

+0

我很困惑。您的意思是驗證*輸入了多少個*字符或輸入了哪些字符? – 2014-10-29 16:26:20

回答

0

好吧,我明白你正在嘗試做的但你正在做一個壞的方式...你將永遠只讀前兩個字符!


此行chrOne + chrTwo不是你期待什麼是。 A在ASCII中與65相同,B = 66等等。所以實際上你總結了兩個數字。 65 + 66 = 131大於3;


我不知道它是壞的格式在這裏StackOverflow上,但while(...)應該來}後。這段代碼不應該編譯。

0

if(chrOne + chrTwo > maxChr)不請檢查是否或不是用戶輸入兩個以上的字符,所以根據我的理解你說這是錯誤的。如果你只需要一個字符,你可以在字符串中輸入用戶信息,並對此進行檢查以查看用戶輸入了多少個字符。

0

您正在使用

cin >>chrOne>>chrTwo; 

比方說,用戶輸入兩個以上的字符即荒謬的問題。

即使這樣僅前兩個字符將被存儲在您的變量,即

chrOne='a' 
chrTwo='b' 

請說明您打算做什麼......

1

一個do...while循環的樣子:

do 
{ 

} while(); 

(你的同時在結束括號之前)

如果你只是想獲得兩個字符(假設你只想0-9你問的問題數):

#include <iostream> 

int main() 
{ 

    char in1,in2; 
    do { 
     std::cout << "please make a selection" 
     cin.get(in1); 
     cin.get(in2); 
     in1 -= '0'; //converts a char to the digit that represents it - needs checking though 
     in2 -= '0'; 
     //at this point, you have grabbed both the inputs from the cmdline. 
     //you'll need to ensure that these are valid. 
    } while (!(in1 >= 0 && in1 <= 9 && in2 >= 0 && in2 <= 9)); //change as needed e.g. if you have a 5*6 machine, reduce the '9's to 5 and 6 

    //you now have your input. 
} 
+0

這個問題是tagget C++。將'getchar()'更改爲'cin' – Quest 2014-10-29 17:00:04

+1

@Quest done。現在使用'cin.get(char&)'每次只抓取一個字符。 – Baldrickk 2014-10-30 09:59:29