C++ visualc&x2B+;不识别
这是一个简单的练习程序C++ visualc&x2B+;不识别,c++,C++,这是一个简单的练习程序 #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 * p
#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;
}
我没有时间输入书名,同时运行booktitle和bookprice。帮助。问题在于,在执行以下操作时,新行字符未从输入流中提取:
cin >> bookno;
最快的方法是在它后面插入一个额外的cin.get()(在您的input()方法中):
cout>bookno;
cin.get();
价格;
另一个建议是尽量避免混合C和C++函数。< /P>为什么你要混合IoFiels+STDIO调用?只需对bookt使用
std::string
,并使用cin
。您确定可能只是没有正确使用它吗?如果你正确使用它,你应该写一个错误报告…我同意Mat的观点,混合使用stdio和streams不是一个好主意。原因是它们使用单独的缓冲。改用std::getline
。我想这与输入缓冲区有关。读取数字(bookno)会将换行保留在缓冲区中(因为换行不是数字的一部分),但读取整行的函数对缓冲区中的单个“\n”感到满意,并认为用户键入了空行。-1:问题标题不好。您认为gets_s()尚未被“识别”,但事实并非如此。“gets_()为什么返回空字符串?”将更清楚地说明这个问题,并可能帮助您找出问题的真正所在。
cin >> bookno;
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;