c++帮助从 stdin 读入到 stdout 。还有运算符重载
我需要有关这部分代码的帮助...我应该将两个双精度数传递给 schmoo。如果我这样做“Schmoo(8.0,9.0);”它可以找到,但是当我尝试它时,我收到一个错误。我应该从 cin 读取输入,看起来像这样“add schmoo 8.0 7.0”我认为我提取的双精度错误,如何正确地从 cin 中提取每个内容。只要他们输入,我就需要继续下去。
while(cin){
string command1 = "add schmoo";
string input;
cin >> input;
double a,b;
if(input == command1){
cin >> a >> b;
Schmoo *a = new Schmoo(a,b);
c.insertFront(a);
}
string command2 = "throw mud";
if(input == command2){
cin >> a >> b;
c.throwMudAt(a,b);
}
另外,我需要帮助重载此操作符:
ostream &operator<<(ostream &os, Schmoo &s){
if(s.getMud() == 1){
os << "Schmoo at (" << s.x << ", " << s.y << ") was hit mud " << mud << "time.";
}
os << "Schmoo at (" << s.x << ", " << s.y << ") was hit with mud" << mud << "times.";
return os;
}
我收到一个与 s.getMud() 有关的错误;我之前已经通过指针使用过 get mud ,但是这个类与任何具有指针的类都不是朋友。但是 getMud 是同一个类的函数,我如何使用 getMud();在此背景下。
I need help regarding this portion of code...I am supposed to be passing two doubles to schmoo. if I do it like this "Schmoo(8.0,9.0);" it works find but when I try it as I have it, I get an error. I am supposed to be reading input from cin which looks like this "add schmoo 8.0 7.0" I think I am extracting the doubles wrong, how to extract each thing from cin properly. I need this to continue as long as their is input.
while(cin){
string command1 = "add schmoo";
string input;
cin >> input;
double a,b;
if(input == command1){
cin >> a >> b;
Schmoo *a = new Schmoo(a,b);
c.insertFront(a);
}
string command2 = "throw mud";
if(input == command2){
cin >> a >> b;
c.throwMudAt(a,b);
}
Also i need help with overloading this opperator:
ostream &operator<<(ostream &os, Schmoo &s){
if(s.getMud() == 1){
os << "Schmoo at (" << s.x << ", " << s.y << ") was hit mud " << mud << "time.";
}
os << "Schmoo at (" << s.x << ", " << s.y << ") was hit with mud" << mud << "times.";
return os;
}
I am getting an error that has to do with s.getMud(); I've used get mud through a pointer before, but this class is no friend with any that has the pointer. but getMud is a function of the same class this is in, how do I use getMud(); in this context.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
cin
读取直到遇到第一个空格,因此input
字符串只会是“add”,而不是“add schmoo”。最好读取第一个字符串,检查它是否为“add”,然后读取下一个字符串(您可能想要添加到多个 schmoo),然后读取 double 。或者将命令更改为“add_schmoo”。对于您的重载,类
Schmoo
是如何定义的?cin
reads until the first whitespace it encounters, so theinput
string will only be "add", not "add schmoo". Better read the first string, check if it is "add", then read the next string (you might want to add to more than schmoo) and then read thedouble
s. Or change the command to "add_schmoo".For your overload, how is the class
Schmoo
defined?您的问题主要来自这一行:
如果您的输入是
add schmoo 8.0 9.0
,则cin >>> input
将不起作用,因为您没有明确指示它何时应该停止读取字符。Your problem is coming primarily from this line:
If your input is
add schmoo 8.0 9.0
, then thecin >> input
will not work, as you have given it no solid indication of when it should stop reading characters.