Reading char by char from a file c++

Sep 18, 2018 at 11:53pm
Hi, I am trying to read each character from a file in c++, also,I need to get their ascii value, but I have a problem on the output, there are two characters else I dont need, even I don´t why they appear.
Here is the code and the output, thanks a lot.

#include <iostream>
#include<fstream>

using namespace std;

int main()
{
ofstream wfile("Ej_01.txt");
wfile<<"AbCd"<<endl;
wfile.close();

ifstream lfile;

lfile.open("Ej_01.txt");
char word;
int temp;
while(lfile.good()){
lfile.get(word);
temp=word;

cout<<word<<" "<<temp<<endl;



}

cout<<endl;

lfile.close();


return 0;


}




And this is the output:

A 65
b 98
C 67
d 100

10

10

Press <RETURN> to close this window...




So How can I get the same result without de last two '10'??
Sep 18, 2018 at 11:57pm
Character '10' is the ASCII code for newline. They are part of the file.

If you don't want to see them, either ignore them or supply a file without any newlines.

Hope this helps.
Sep 19, 2018 at 1:10am
Thanks, I understand it better, but I still have a little problem: It is reading twice the last caracter, so now this is the output:

A 65
b 98
C 67
d 100
d 100
Press <RETURN> to close this window...


As you can see...It prints (d 100) twice
Sep 19, 2018 at 3:59am
> It is reading twice the last caracter

Check for input failure after (not before) attempted input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <fstream>
#include <cctype>

int main()
{
    std::ifstream file( __FILE__ ) ;

    char c ;
    while( file.get(c) ) // exit the loop if input failed (no more characters in the file) 
    {
        if( std::isprint(c) ) std::cout << c << ' ' << int(c) << '\n' ;
    }
}
Topic archived. No new replies allowed.