我在这段代码中遇到了这个问题,当我编译时,在函数 gets 中向我显示错误,这说明我可以将 gets 更改为 getw,但是当我再次执行此操作时,机器向我显示错误。我用C++14
#include<iostream>
using namespace std;
class Maleta{
private:
char *color; //declaracion de variables ---documentando
char *material;
char *marca;
int precio;
public:
void entrada (void); //Declaracion de metodos
void proceso (void);
void salida (void);
};
void Maleta::entrada()
{
cout<<"de color "<<endl;
gets(color);
cout<<"de material"<<endl;
gets(material);
cout<<"de marca"<<endl;
gets(marca);
cout<<"de precio"<<endl;
cin>>precio;
}
void Maleta::salida(void)
{
cout<<"color :"<<color<<endl;
cout<<"material :"<<material<<endl;
cout<<"marca :" <<marca<<endl;
cout<<"precio :"<<precio<<endl;
}
int main()
{
Maleta morral;
morral.entrada();
morral.salida();
}`
我想用函数 gets 修复错误。
gets()
函数已被弃用,不应使用。通过使用 C++ 字符串和 getline
,您可以让您的生活变得更加轻松。这是代码的固定版本:
#include <iostream>
#include <string>
using namespace std;
class Maleta {
private:
string color; // I changed these to C++ strings
string material;
string marca;
int precio;
public:
void entrada(void);
void proceso(void);
void salida(void);
};
void Maleta::entrada() {
cout << "de color " << endl;
getline(cin, color); //Note that instead of gets, we are using getline for these strings
cout << "de material" << endl;
getline(cin, material);
cout << "de marca" << endl;
getline(cin, marca);
cout << "de precio" << endl;
cin >> precio; //We can keep your use of cin for precio since it is an int
cin.ignore(); // Clear newline from the buffer
}
void Maleta::salida(void) {
cout << "color :" << color << endl;
cout << "material :" << material << endl;
cout << "marca :" << marca << endl;
cout << "precio :" << precio << endl;
}
int main() {
Maleta morral;
morral.entrada();
morral.salida();
}