如何在 C++ 中逐个字符地从文本文件中读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12240010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Read from a Text File, Character by Character in C++
提问by Toby
I was wondering if someone could help me figure out how to read from a text file in C++, character by character. That way, I could have a while loop (while there's still text left) where I store the next character in the text document in a temp variable so I could do something with it, then repeat the process with the next character. I know how to open the file and everything, but temp = textFile.getchar()
doesn't seem to work. Thanks in advance.
我想知道是否有人可以帮助我弄清楚如何从 C++ 中的文本文件中逐个字符地读取。这样,我可以有一个 while 循环(虽然还有文本剩余),我将文本文档中的下一个字符存储在临时变量中,以便我可以对它做一些事情,然后对下一个字符重复该过程。我知道如何打开文件和所有内容,但temp = textFile.getchar()
似乎不起作用。提前致谢。
回答by cnicutar
You could try something like:
你可以尝试这样的事情:
char ch;
fstream fin("file", fstream::in);
while (fin >> noskipws >> ch) {
cout << ch; // Or whatever
}
回答by Jerry Coffin
@cnicutar and @Pete Becker have already pointed out the possibility of using noskipws
/unsetting skipws
to read a character at a time without skipping over white space characters in the input.
@cncutar 和 @Pete Becker 已经指出使用noskipws
/unsetting 一次skipws
读取一个字符而不跳过输入中的空白字符的可能性。
Another possibility would be to use an istreambuf_iterator
to read the data. Along with this, I'd generally use a standard algorithm like std::transform
to do the reading and processing.
另一种可能性是使用 anistreambuf_iterator
来读取数据。除此之外,我通常会使用标准算法std::transform
来进行读取和处理。
Just for example, let's assume we wanted to do a Caesar-like cipher, copying from standard input to standard output, but adding 3 to every upper-case character, so A
would become D
, B
could become E
, etc. (and at the end, it would wrap around so XYZ
converted to ABC
.
举个例子,假设我们想要做一个类似 Caesar 的密码,从标准输入复制到标准输出,但是每个大写字符加 3,所以A
会变成D
,B
可能会变成E
等等(最后,它会环绕所以XYZ
转换为ABC
.
If we were going to do that in C, we'd typically use a loop something like this:
如果我们要在 C 中做到这一点,我们通常会使用这样的循环:
int ch;
while (EOF != (ch = getchar())) {
if (isupper(ch))
ch = ((ch - 'A') +3) % 26 + 'A';
putchar(ch);
}
To do the same thing in C++, I'd probably write the code more like this:
要在 C++ 中做同样的事情,我可能会更像这样编写代码:
std::transform(std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(std::cout),
[](int ch) { return isupper(ch) ? ((ch - 'A') + 3) % 26 + 'A' : ch;});
Doing the job this way, you receive the consecutive characters as the values of the parameter passed to (in this case) the lambda function (though you could use an explicit functor instead of a lambda if you preferred).
以这种方式完成这项工作,您将收到连续字符作为传递给(在本例中)lambda 函数的参数值(尽管如果您愿意,您可以使用显式函子而不是 lambda)。
回答by user515430
To quote Bjarne Stroustrup:"The >> operator is intended for formatted input; that is, reading objects of an expected type and format. Where this is not desirable and we want to read charactes as characters and then examine them, we use the get() functions."
引用 Bjarne Stroustrup 的话:“>> 运算符用于格式化输入;也就是说,读取预期类型和格式的对象。如果这是不可取的并且我们希望将字符读取为字符然后检查它们,我们使用 get () 职能。”
char c;
while (input.get(c))
{
// do something with c
}
回答by mike
//Variables
char END_OF_FILE = '#';
char singleCharacter;
//Get a character from the input file
inFile.get(singleCharacter);
//Read the file until it reaches #
//When read pointer reads the # it will exit loop
//This requires that you have a # sign as last character in your text file
while (singleCharacter != END_OF_FILE)
{
cout << singleCharacter;
inFile.get(singleCharacter);
}
//If you need to store each character, declare a variable and store it
//in the while loop.
回答by Dr. Jekyll
Here is a c++ stylish function your can use to read files char by char.
这是一个 C++ 时尚的函数,您可以使用它逐个字符读取文件。
void readCharFile(string &filePath) {
ifstream in(filePath);
char c;
if(in.is_open()) {
while(in.good()) {
in.get(c);
// Play with the data
}
}
if(!in.eof() && in.fail())
cout << "error reading " << filePath << endl;
in.close();
}
回答by Pete Becker
Re: textFile.getch()
, did you make that up, or do you have a reference that says it should work? If it's the latter, get rid of it. If it's the former, don't do that. Get a good reference.
回复:textFile.getch()
,你是编造的,还是有参考资料说它应该有效?如果是后者,请摆脱它。如果是前者,请不要这样做。得到一个很好的参考。
char ch;
textFile.unsetf(ios_base::skipws);
textFile >> ch;
回答by zwol
There is no reason not to use C <stdio.h>
in C++, and in fact it is often the optimal choice.
<stdio.h>
在 C++ 中没有理由不使用 C ,事实上它往往是最佳选择。
#include <stdio.h>
int
main() // (void) not necessary in C++
{
int c;
while ((c = getchar()) != EOF) {
// do something with 'c' here
}
return 0; // technically not necessary in C++ but still good style
}
回答by Drew Dormann
Assuming that temp
is a char
and textFile
is a std::fstream
derivative...
假设它temp
是一个char
并且textFile
是一个std::fstream
导数......
The syntax you're looking for is
您正在寻找的语法是
textFile.get( temp );