Reputation: 669
In C, suppose I need to take input from a string
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 book at 12
OUTPUT
Quantity of item is: 1
The cost of item is: 12
The name of item is: book
Now I want to do the same thing in 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? Please help.
Upvotes: 2
Views: 454
Reputation: 503
You could use iostream's 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*.
Or streamline the cin's as cin >> num >> cost >> name;
Also, as Griwes noted, you will want to perform error checking on your results.
Upvotes: 0
Reputation: 13661
In c++, std::stream provides the read and write communication with the user through the >>
operator.
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;
Upvotes: 0
Reputation: 1669
In C++ you should rather use cin
, cout
and string
from standard library.
Upvotes: 0
Reputation: 393934
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
Upvotes: 6