开发者

c++ Help with reading in from stdin and to stdout . Also Operator overloading

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){
    开发者_StackOverflow中文版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.


cin reads until the first whitespace it encounters, so the input 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 the doubles. Or change the command to "add_schmoo".


For your overload, how is the class Schmoo defined?


Your problem is coming primarily from this line:

string input;
cin >> input;

If your input is add schmoo 8.0 9.0, then the cin >> input will not work, as you have given it no solid indication of when it should stop reading characters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜