所以这是一个简单的练习计划。
#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。帮助
答案 0 :(得分: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 ++函数。