忽略C ++ Cin中的逗号 [英] Ignoring commas in c++ cin

查看:574
本文介绍了忽略C ++ Cin中的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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";

但这总是返回(0,0)(0,0)。

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

cin.ignore的正确实现是什么?

What would the correct implementation of cin.ignore be?

推荐答案

如果从字面上输入在数据中以(x1,y1)(x2,y2)的形式出现,例如

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

(10,20) (30,40)

然后您将需要消耗括号和逗号。一种简单的方法是声明一个char变量,并使用该变量来获取需要删除的单个字符

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.

这篇关于忽略C ++ Cin中的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆