是否可以将数据类型视为输入流?

发布于 2024-08-22 13:08:24 字数 542 浏览 4 评论 0原文

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 有 2 个字符的行,因此如果它有“9r”,“9r”将存储在 move 的数据成员中(我将其公开只是为了方便)。为了确保这一点有效,我输出了 move 的数据,并且果然它有效

我想做的是使用相同的运算符,但不是从文件或标准输入中获取输入,我将拥有一个包含所需数据的数据成员输入。因此,在 main 中,如果我有一个带有“1d”的 char 数组,我需要能够使用相同的函数(不修改它)来执行相同的操作。

这可能吗?任何帮助表示赞赏。

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 main, 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

债姬 2024-08-29 13:08:24

您可以使用stringstream

#include <sstream>

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

You can use a stringstream:

#include <sstream>

int main() {
    char foo[] = "1d";
    std::stringstream ss(foo);
    Move move;
    ss >> move;
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文