我正在尝试从 stdio 迁移到 iostream,事实证明这非常困难。我已经掌握了加载文件和关闭文件的基础知识,但我真的不知道流是什么,或者它们如何工作。
与此相比,在工作室中一切都相对简单和直接。我需要做的是
- 从文本文件中读取单个字符。
- 根据该字符的含义调用函数。
- 重复此操作,直到读完文件中的所有字符。
到目前为止我所拥有的是..不多:
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;
}
我需要知道的是如何获取单个字符以及该字符实际上是如何存储的(它是字符串吗?int?字符?我可以自己决定如何存储它吗?)
一旦我知道我认为我可以处理剩下的事情。我会将角色存储在适当的容器中,然后使用开关根据该角色的实际情况执行操作。它看起来像这样。
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 ' ':
//dosomething etc etc
break;
case '\n':
}
}
return 0;
}
请注意,我需要能够检查空白和新行,希望这是可能的。如果我可以将数字存储在 int 中并将字符存储在 char 中,而不是使用通用容器,那也会很方便。如果没有的话我可以解决它。
感谢任何可以向我解释流如何工作以及它们的可能性的人。
您还可以抽象出获得单个角色的整个想法streambuf_iterator
s,如果你想使用任何算法:
#include <iterator>
#include <fstream>
int main(){
typedef std::istreambuf_iterator<char> buf_iter;
std::fstream file("name");
for(buf_iter i(file), e; i != e; ++i){
char c = *i;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)