开发者

Is it possible to treat datatypes as an input stream?

开发者 https://www.devze.com 2022-12-20 15:10 出处:网络
int main(int argc, char *argv[]) { Move move; ifstream inf(\"eof.txt\"); inf >> move; return 0; } istream& operator>> (istream &is, Move &move)
int main(int argc, char *argv[])
{
  Move move;
  ifstream inf("eof.txt");
  inf >> move;
  return 0;
}

istream& operator>> (istream &is, Move &move)
{ 
  is >> move.c; // c = char c[2];
  cout << move.c << endl;
  return is;
}

eof.txt has lines of 2 chars, so if it had "9r", "9r" would be stored in move's data member (I made it public just for ease). To make sure this works I output the data of move and sure enough it works

What I'm trying to do is use this same operator, but instead of getting input from say a file or stdin, I will have a datamember that holds the desired input. Thus in ma开发者_开发问答in, if I have a char array with "1d", I need to be able to use the same function (without modifying it) to do the same thing.

Is this possible? Any help appreciated.


You can use a stringstream:

#include <sstream>

int main() {
    char foo[] = "1d";
    std::stringstream ss(foo);
    Move move;
    ss >> move;
    return 0;
}
0

精彩评论

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