2013-01-05 23 views
-5

首先thnx試圖幫助我.....這是我的程序的一部分......我想知道如何把輸入數據的驗證主( ).... thnx在C++程序中的驗證

#include<stdio.h> 
#include<iostream.h> 
#include<conio.h> 
    int i; 

class product   //start of class 
    { 


      int itemno; 
      char name[100]; 
      char itemtype[50]; 
      float price; 
      float quantity; 
      float total; 


      public: 

      void addprod() ; 
      void calculate(); 
      void accept(); 
      void display() ; 




    } ;     //end of class 




    void product::addprod() //starting of addproduct() 
     { 
      cout<<"enter the serial number"; 
      cin>>itemno; 

      cout<<"enter the name of the poduct:"; 
      gets(name) ; 

      cout<<"enter its type:"; 
      gets(itemtype); 

      ***cout<<"enter its price:"; 
      cin>>price;** 
     }*          //end of addproduct() 



    void product::accept()   //starting of accept() 
    { 
      cout<<"enter the item name:"; 
      gets(name) ; 


      cout<<"enter the quantity:"; 
      cin>>quantity; 

    } 




    void product::calculate() 
     { 
        total=price*quantity; 
     } 



    void product::display() 
     { 
       cout<<"\nName"; 
       cout<<name; 

       cout<<"\nPrice"; 
       cout<<price ; 
       cout<<"\nquantity"; 
       cout<<quantity; 
       cout<<"\ntotal\n\n\n\n\n"; 
       cout<<total; 

     } 





     void main() 
     { 
     int ch; 
     product s1[3]; 

     a: 

     cout<<"\n  1.  Add product one by one"; 
     cout<<"\n  2.  Add products in bulk"; 
     cout<<"\n  3.  Make Bill"; 
     cout<<"\n  4.  Display Bill"; 
     cout<<"\n  0.  Exit"; 
     cout<<"\n  Enter your choise(1,2,3,9)"  ; 
     cin>>ch; 


     switch(ch) 
     { 

     **case 1:   cout<<"\n press n to exit\n\n"; 
           char con='y'; 
           while(con=='y') 
           { 
           s1[i].addprod(); 
           i++; 
           cout<<"do u wanna continue(y/n)"; 
           cin>>con; 
             if(con=='n') 
             { 
             goto a; 
          } 
           } 
           break; 
      }** 

這是我的學校項目,所以需要儘快提供幫助。 一樣,如果一個人進入一個字符(A,B,C),所以我應該怎麼做才能讓他意識到了一個錯誤的輸入,並要求用戶輸入正確的形式

+8

首先對'main'使用符合的簽名,而不是使用'goto',並使代碼格式可讀。 – chris

+2

請給出具體問題。 SO不是「轉儲你的家庭作業和運行」網站。 – Linuxios

+1

並請修復您的縮進。 – Linuxios

回答

-2

可以測試與輸入成功如果

if (cin >> ch) 
    ... 

要求用戶再次輸入輸入,你需要一個循環,你還需要調用cin.clear()恢復流的狀態:

cout << "\n  Enter your choice(1,2,3,9)": 

cin >> ch; 
while (!cin) 
{ 
    cout << "Invalid input. Please try again." << endl; 

    cin.clear(); 
    cin >> ch; 
} 

這就是你如何處理main中的第一個輸入項目。你可以爲其他人做類似的事情。

+0

cin.clear()使用哪個頭文件 –

+0

它是** cin **的成員,所以顯然它聲明在** cin **(或** basic_istream **實際)聲明的相同頭文件中。只需包含iostream或iostream.h即可。 – user1610015