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.
We use the getc() and putc() I/O functions to read a character from a file and write a character to a file respectively. Syntax of getc: char ch = getc(fptr); Where, fptr is a file pointer.
fgetc()– This function is used to read a single character from the file. fgets()– This function is used to read strings from files. fscanf()– This function is used to read formatted input from a file.
C – Read Single Character using Scanf() So, to read a single character from console, give the format and argument to scanf() function as shown in the following code snippet. char ch; scanf("%c", ch); Here, %c is the format to read a single character and this character is stored in variable ch .
fgetc() function is used to read a single character from a file at a time.
You could try something like:
char ch;
fstream fin("file", fstream::in);
while (fin >> noskipws >> ch) {
cout << ch; // Or whatever
}
@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.
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.
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
.
If we were going to do that in C, we'd typically use a loop something like this:
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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With