小编Jcr*_*ack的帖子

从fstream中读取单个字符?

我正试图从stdio转移到iostream,这证明非常困难.我已经掌握了加载文件并关闭文件的基础知识,但我真的不知道什么是流甚至是什么,或者它们是如何工作的.

在stdio中,与此相比,一切都相对容易和直接.我需要做的是

  1. 从文本文件中读取单个字符.
  2. 根据该角色调用函数.
  3. 重复,直到我读完文件中的所有字符.

到目前为止我所拥有的......并不多:

int main()
{
    std::ifstream("sometextfile.txt", std::ios::in);
    // this is SUPPOSED to be the while loop for reading.  I got here and realized I have 
    //no idea how to even read a file
    while()
    {
    }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我需要知道的是如何获得单个字符以及该字符实际存储的方式(它是一个字符串吗?一个int?一个char?我可以自己决定如何存储它吗?)

一旦我知道我认为我可以处理其余的事情.我将角色存储在适当的容器中,然后使用开关根据角色的实际情况做事.它看起来像这样.

int main()
{
    std::ifstream textFile("sometextfile.txt", std::ios::in);

    while(..able to read?)
    {
        char/int/string readItem;
        //this is where the fstream would get the character and I assume stick it into readItem?
        switch(readItem)
        {
        case 1:
            //dosomething
              break;
        case …
Run Code Online (Sandbox Code Playgroud)

c++ file-io fstream iostream

8
推荐指数
2
解决办法
2万
查看次数

有人可以解释多态性的好处吗?

所以我几乎了解它是如何工作的,但我无法理解它是什么使它有用.您仍然必须定义所有单独的函数,您仍然必须创建每个对象的实例,所以为什么不从该对象调用该函数与创建对象,创建指向父对象的指针并传递派生对象引用,只是为了调用一个函数?我不明白采取这一额外步骤的好处.

为什么这样:

class Parent
{
    virtual void function(){};
};

class Derived : public Parent
{
    void function()
    {
    cout << "derived";
    }
};

int main()
{
    Derived foo;
    Parent* bar = &foo;
    bar->function();
    return -3234324;
}
Run Code Online (Sandbox Code Playgroud)

对此:

class Parent
{
    virtual void function(){};
};

class Derived : public Parent
{
    void function()
    {
    cout << "derived";
    }
};

int main()
{
    Derived foo;
    foo.function();
    return -3234324;
}
Run Code Online (Sandbox Code Playgroud)

他们做的完全一样吗?据我所知,只有一个人使用更多的记忆和更多的混乱.

c++ polymorphism

7
推荐指数
2
解决办法
2万
查看次数

使用C API时,请使用字符数组或使用字符串并根据需要进行转换?

我正在使用C API,许多函数接受字符数组的参数.我听说使用char数组现在不受欢迎了.但另一方面,使用c_str()将字符串转换为char数组反复过来似乎很浪费.

是否有任何理由以一种方式与另一种方式进行?

c++ arrays string

4
推荐指数
1
解决办法
120
查看次数

流的fscanf类型函数?

我习惯使用fscanf进行简单的文件输入,因为它使它变得简单.我试图转移到溪流,我希望能够做到这一点:

fscanf(file, %d %s, int1, str1);
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,通过一个文件读取相对容易,将第一个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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

正如你所知道的那样,这有几个原因非常糟糕,而且我从来没有真正使用它,但这是我能想到的全部.有没有更好的方法来解决这个问题?

c++ file-io fstream iostream

1
推荐指数
1
解决办法
1102
查看次数

标签 统计

c++ ×4

file-io ×2

fstream ×2

iostream ×2

arrays ×1

polymorphism ×1

string ×1