流的 fscanf 类型函数?

发布于 2025-01-03 01:19:31 字数 719 浏览 3 评论 0原文

我习惯使用 fscanf 进行简单的文件输入,因为它使事情变得简单。我正在尝试转移到流,但我希望能够做到这一点:

fscanf(file, %d %s, int1, str1);

如您所见,读取文件相对容易,将您遇到的第一个 int 粘贴到一个容器中,然后将第一个字符串粘贴到一个容器中转换为 char*。我想要的是使用流函数通过 fstreams 来完成此操作。这是我以我有限的流知识想出来的。

while((fGet = File.get() != EOF))
{
    int x;
    int y;
    bool oscillate = false;
    switch(oscillate)
    {
    case false:
        {
            x = fGet;
            oscillate = true;
            break;
        }
    case true:
        {
            y = fGet;
            oscillate = false;
            break;
        }
    }
}

基本上我想扫描一个文件并将第一个 int 放入 x 中,将第二个 int 放入 y 中。

正如您所知,由于某些原因,这非常糟糕,而且我从未真正使用过它,但这就是我能想到的。有更好的方法来解决这个问题吗?

I'm used to using fscanf for simple file input, because it makes it simple. I'm trying to move to streams though and I'd like to be able to do this:

fscanf(file, %d %s, int1, str1);

as you can see it's relatively easy to read through a file, stick the first int you come across into one container, and then the first string into a char*. What I want, is to do this with fstreams, using stream functions. This is what I came up with, with my limited stream knowledge.

while((fGet = File.get() != EOF))
{
    int x;
    int y;
    bool oscillate = false;
    switch(oscillate)
    {
    case false:
        {
            x = fGet;
            oscillate = true;
            break;
        }
    case true:
        {
            y = fGet;
            oscillate = false;
            break;
        }
    }
}

Basically I want to scan through a file and put the first int into x, and the second into y.

This is pretty bad for a few reasons, as you can tell, and I'd never actually use this but it's all I can think of. Is there a better way to go about this?

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

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

发布评论

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

评论(1

看轻我的陪伴 2025-01-10 01:19:31

要从流中读取两个整数,您所要做的就是

int x, y;
File >> x >> y;

And 相当于

fscanf(file, "%d %s", &int1, str1);

Is

int x;
string s;

file >> x >> s;

And 确保如果您想检查读取是否有效,请将读取放入条件:

if (file >> x >> s)

while (file >> x >> y)

或其他条件中。

To read two integers from a stream, all you have to do is

int x, y;
File >> x >> y;

And the equivalent of

fscanf(file, "%d %s", &int1, str1);

Is

int x;
string s;

file >> x >> s;

And make sure that if you want to check whether the reads worked, put the reads in the condition:

if (file >> x >> s)

or

while (file >> x >> y)

or whatever.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文