简体   繁体   English

通过C ++中的字符串获取输入

[英]Taking Input through a string in c++

In C, suppose I need to take input from a string 在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 INPUT

1 book at 12 1本书在12

OUTPUT OUTPUT

Quantity of item is: 1 项目数量为:1

The cost of item is: 12 该物品的成本是:12

The name of item is: book 项目的名称是:书

Now I want to do the same thing in C++. 现在我想在C ++中做同样的事情。 And I have no idea how to approach. 而且我不知道该如何处理。 gets() returns the whole string.Is there any specific function that I am missing out on? gets()返回整个字符串,是否有我遗漏的特定功能? Please help. 请帮忙。

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 */ }

You will want to add errorhandling 您将要添加错误处理

在C ++中,您应该使用标准库中的cincoutstring

You could use iostream's cin. 您可以使用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;

and then of course you could also use std::string instead of char*. 然后当然也可以使用std :: string代替char *。

Or streamline the cin's as cin >> num >> cost >> name; 或者将cin简化为cin >> num >> cost >>名称;

Also, as Griwes noted, you will want to perform error checking on your results. 另外,正如Griwes指出的那样,您将需要对结果进行错误检查。

In c++, std::stream provides the read and write communication with the user through the >> operator. 在c ++中, std :: stream通过>>运算符与用户进行读写通信。

Your code translates to 您的代码转换为

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM