Visual C++ not identifying gets_s

Visual C++ not identifying gets_s

本文关键字:gets identifying C++ not Visual      更新时间:2023-10-16

所以这是一个简单的练习程序。

#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

它只是没有给我时间输入书名,同时运行书名和书价。帮助

问题是,当您这样做时,不会从输入流中提取新行字符:

cin >> bookno;

最快的方法是在cin.get()之后(在input()方法中)插入一个额外的cin.get

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++函数。