Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

std - Ignoring commas in c++ cin

I have the following code:

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

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

What would the correct implementation of cin.ignore be?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 need to be removed

float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
char eater;
std::cout << "Enter coordinates as "(x1,y1) (x2,y2)"
";
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)"
";
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...