2012-02-08 44 views
-1

因此,這是用於實踐一個簡單的程序。視覺C++不標識gets_s

#include "stdafx.h" 
#include "iostream" 
#include "conio.h" 
#include "stdio.h" 

using namespace std; 

class book 
{ 
    int bookno; 
    char bookt[20]; 
    float price; 
    float totalcost(int n) 
    { 
     float tot; 
     tot = n * price; 
     return tot; 
    } 
public: 
    void input() 
    { 
     cout << "\nEnter book number: "; 
     cin >> bookno; 
     cout << "\nEnter book title: "; 
     gets_s(bookt);     //Does not identify this. 
     cout << "\nEnter book price: "; 
     cin >> price; 
    } 
    void purchase() 
    { 
     int n; 
     float total; 
     cout << "\nEnter the number of books to be purchase: "; 
     cin >> n; 
     total = totalcost(n); 
     cout << "\nTotal amount is: " << total; 
    } 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    book B1; 
    B1.input(); 
    B1.purchase(); 
    _getch(); 
    return 0; 
} 

編譯器(Visual C++ 2010)不識別gets_s。在這個意義上確定,它只是跳過輸入字段的輸出如下:

OUTPUT 

Enter book number: 5 

Enter book title: 
Enter book price: 5 

Enter the number of books to be purchased: 5 

Total amount is: 25 

它只是不給我時間進入書名並運行在同一時間BOOKTITLE和bookprice。幫幫我。

+3

你爲什麼混合iostream和stdio的電話?只需使用'std :: string'作爲bookt並使用'cin'。 – Mat 2012-02-08 11:03:21

+0

你確定可能你沒有正確使用它嗎?如果你正確使用它,你應該寫一個bugreport ... – PlasmaHH 2012-02-08 11:17:06

+0

我同意Mat,mixin stdio和streams不是一個好主意。原因是他們使用單獨的緩衝。改爲使用'std :: getline'。 – 2012-02-08 11:22:47

回答

0

的問題是,新行字符不從輸入流中提取,當你做:

cin >> bookno; 

最快捷的方式爲您將插入後,一個額外的cin.get()(在你的input()方法):

cout << "\nEnter book number: "; 
cin >> bookno; 
cin.get(); 
cout << "\nEnter book title: "; 
gets_s(bookt);     // Now it will identify this. 
cout << "\nEnter book price: "; 
cin >> price; 

另一個建議是儘量避免混合使用C和C++函數。