在cpp

时间:2015-10-19 09:03:49

标签: c++ class constructor new-operator dynamic-allocation

我有3个名为Starter,Pizza和Dessert的类,每当创建一个对象时,它会接受可变数量的字符串输入,

//pizza takes 2 inputs
Pizza p("margarita","large size");

//starter takes 3 inputs
Starter s("ribs","bbq sauce","small size");

但我想使用add()函数创建一个 new 对象,该函数接受一个字符串并将其与类匹配以创建一个新对象。例如

add(string type)
{
   if(type == "Pizza")
   {
     Pizza *p = new Pizza();
   }

   else if(type == "Starter ")
   {
     Starter *p = new Starter ();
   }
}

现在我的问题是,如何以用户友好的方式向类提供输入?通过用户友好,我认为用户可以在一行中编写类的所有输入,而不是使用cin来获取每一个输入。

说我们正在拿披萨,那就是我不想要的,

cout<<"What type of pizza";
cin>>*input* <<endl;
cout<<"What size";
cin>>*input* <<endl;

我想在一行中写下所有输入,如

输入“margarita”,“大”

2 个答案:

答案 0 :(得分:2)

// Read complete string.
// Eg. margarita large
string order;
getline(cin, order);

// It automatically parses string based on space
istringstream is(order);
string meal, size;
is >> meal;
is >> size;

答案 1 :(得分:1)

归功于@MuratKarakus。只是扩展他的答案以支持这种类型的输入"margarita","large"

// Read complete string.
// Eg. margarita large
string order;
getline(cin, order);

std::replace( order.begin(), order.end(), ',', ' '); // this'll replace all ',' with space

// It automatically parses string based on space
istringstream is(order);
string meal, size;
is >> meal;
is >> size;    

--------更新

下面的代码是支持"1/2 margarita 1/2 bbq delux", "large"

之类的输入
// Read complete string.
// Eg. margarita large
string order;
getline(cin, order);
std::replace( order.begin(), order.end(), ' ', '-'); // this'll replace all space with '-'
std::replace( order.begin(), order.end(), ',', ' '); // this'll replace all ',' with space
// It automatically parses string based on space
istringstream is(order);
string meal, size;
is >> meal;
std::replace( meal.begin(), meal.end(), '-', ' '); // this'll replace all '-' with space

is >> size;