我正试图从stdio转移到iostream,这证明非常困难.我已经掌握了加载文件并关闭文件的基础知识,但我真的不知道什么是流甚至是什么,或者它们是如何工作的.
在stdio中,与此相比,一切都相对容易和直接.我需要做的是
到目前为止我所拥有的......并不多:
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) 所以我几乎了解它是如何工作的,但我无法理解它是什么使它有用.您仍然必须定义所有单独的函数,您仍然必须创建每个对象的实例,所以为什么不从该对象调用该函数与创建对象,创建指向父对象的指针并传递派生对象引用,只是为了调用一个函数?我不明白采取这一额外步骤的好处.
为什么这样:
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 API,许多函数接受字符数组的参数.我听说使用char数组现在不受欢迎了.但另一方面,使用c_str()将字符串转换为char数组反复过来似乎很浪费.
是否有任何理由以一种方式与另一种方式进行?
我习惯使用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.
正如你所知道的那样,这有几个原因非常糟糕,而且我从来没有真正使用它,但这是我能想到的全部.有没有更好的方法来解决这个问题?