从fstream读取单个字符? [英] Reading a single character from an fstream?
问题描述
我想从stdio移动到iostream,这是非常困难的。我有一个基本的加载文件和关闭它们,但我真的没有一个线索,甚至一个流甚至是,或它们如何工作。
I'm trying to move from stdio to iostream, which is proving very difficult. I've got the basics of loading a file and closing them, but I really don't have a clue as to what a stream even is yet, or how they work.
在stdio一切都比较容易和直截了当的比较。我需要做的是
In stdio everything's relatively easy and straight forward compared to this. What I need to be able to do is
- 从文本文件中读取单个字符。
-
$ b $
我到目前为止没有多少:
What I have so far is.. not much:
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?一个char?我可以自己决定如何存储它吗?)
What I need to know is how to get a single character and how that character is actually stored(Is it a string? An int? A char? Can I decide for myself how to store it?)
一旦我知道我想我可以处理其余的部分。我将字符存储在一个合适的容器中,然后使用开关根据实际是什么字符做事情。它看起来像这样。
Once I know that I think I can handle the rest. I'll store the character in an appropriate container, then use a switch to do things based on what that character actually is. It'd look something like this.
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和chars在一个字符。
Notice that I need to be able to check for white space and new lines, hopefully it's possible. It would also be handy if instead of one generic container I could store numbers in an int and chars in a char. I can work around it if not though.
感谢任何人能够向我解释流如何工作,以及他们可能做什么。
Thanks to anyone who can explain to me how streams work and what all is possible with them.
推荐答案
你也可以抽象出一个用 streambuf_iterator
想要使用任何算法:
You also can abstract away the whole idea of getting a single character with streambuf_iterator
s, if you want to use any algorithms:
#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;
}
}
这篇关于从fstream读取单个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!