在C中,假设我需要从字符串中获取输入
int num,cost;
char *name[10];
printf("Enter your inputs [quantity item_of_name at cost]");
scanf("%d%*c%s%*c%*s%*c%d",&num,name[0],&cost);
printf("quantity of item: %d",num);
printf("the cost of item is: %d",cost);
printf("the name of item is: %d",name[0]);
INPUT
1本书12岁
输出
项目数量为:1
项目的费用是:12
项目名称为:book
现在我想在C ++中做同样的事情。我不知道如何接近。 gets()返回整个字符串。是否有任何我错过的特定函数?请帮忙。
答案 0 :(得分:6)
int num,cost;
std::string name;
std::cout << "Enter your inputs [quantity item_of_name at cost]: ";
if (std::cin >> num >> name >> cost)
{ } else
{ /* error */ }
您需要添加错误处理
答案 1 :(得分:0)
在C ++中,您应该使用标准库中的cin
,cout
和string
。
答案 2 :(得分:0)
你可以使用iostream的cin。
int num,cost;
char *name[10];
std::cout <<"Enter your quantity"<<std::endl;
std::cin>> num;
std::cout<<" Enter the cost"<<std::endl;
std::cin>>cost;
std::cout<<"Enter the name"<<std::endl;
std::cout<<"The quantity of the item is: "<<num<<" costing: "<<cost<<" for "<<name[0]<<std::endl;
当然你也可以使用std :: string而不是char *。
或者将cin简化为cin&gt;&gt; num&gt;&gt;费用&gt;&gt;名;
此外,正如 Griwes 所述,您需要对结果执行错误检查。
答案 3 :(得分:0)
在c ++中,std::stream通过>>
运算符提供与用户的读写通信。
您的代码转换为
int num,cost;
std::string name;
std::cout << "Enter your inputs [quantity item_of_name at cost]" << std::flush;
std::cin >> num >> name;
std::cin >> at; // skip the at word
std::cin >> cost;
std::cout << "quantity of item: " << num << std::endl;
std::cout << "the cost of item is: " << cost << std::endl;
std::cout << "the name of item is: " << name << std::endl;