Ignoring commas in c++ cin

余生长醉 提交于 2019-12-11 23:01:41

问题


I have the following code:

float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
cin >> x1;
cin.ignore(1, ',');
cin >> y1;
cin >> x2;
cin.ignore(1, ',');
cin >> y2;
cout << "Coordinates registered as (" << x1 << "," << y1 << "), (" << x2 << "," << y2 << ").\n";

But this always returns (0,0) (0,0).

What would the correct implementation of cin.ignore be?


回答1:


If you are literally entering in the data in the form of (x1,y1) (x2,y2) like

(10,20) (30,40)

Then you are going to need to consume the parenthesis as well as the commas. A simple way to do this is to declare a char variable and use that to get the single characters that needs to be removed

float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
char eater;
std::cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
std::cin >> eater; // removes (
std::cin >> x1;
std::cin >> eater; // removes ,
std::cin >> y1;
std::cin >> eater; //removes )
std::cin >> eater; // removes (
std::cin >> x2;
std::cin >> eater; // removes ,
std::cin >> y2;
std::cin >> eater; //removes )

To make it a little more compact you can get one coordinate per line like

float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
char eater;
std::cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
std::cin >> eater >> x1 >> eater >> y1 >> eater;
//            (              ,              )
std::cin >> eater >> x2 >> eater >> y2 >> eater;
//            (              ,              )

I like to leave the comment in there to to express what should be being consumed each time you get the input.



来源:https://stackoverflow.com/questions/33106519/ignoring-commas-in-c-cin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!