Help with input and output of character.

I want to store a char with any ascii value(in the range 0-255) in a .txt file or.bin file or anything.
And again I should be able to take input from that file of the same character. Can i do this with something simple like getchar,putchar,cout<<c,cin>>c,where c is a character.(Language used is c++).

Well, using cin and cout as you pointed out, will allow you to read and write a char from C standard input and to C standard output( i.e. the console window).

To do it using files you need to define new file input and output streams and use those instead of the standard one…

To define such streams you need to include the header #include <fstream> and do something like:

ifstream fin("input_file_name.txt");

ofstream fout("output_file_name.txt");

Nothing should prevent you from reading/writing characters to files, as if you can read strings and they are basically “arrays” of characters, I’d say you should be fine!! Simply use now fin/fout instead of cin/cout and you should be able to accomplish your task :wink:

Good luck,
Bruno

2 Likes

Here is a way,
You just read char with cin>>c;
then convert it to ASCII using a=int© where a is integer variable,
then store a into file .txt,
read ascii from .txt,
now you can convert ASCII to char using c=char(a),

sample code for conversion

#include <iostream>
using namespace std;
int main(){
	char c;
	int a;
	cin >> c;
	cout << "Its ascii value is: " <<int(c)<< endl;
	cin >> a;
	cout << "The character is :" <<char(a)<< endl;
	return 0;
}        

cin and cout takes characters which have values from(0-127) ,but i want to store character with ascii values from(0-255),or basically i want to store a byte(with all possible values from 0-255).

I am doing a compression project . So, can anyone help me out to figure out this,so that i can complete it early.Thanks in advance

Figured out the solution,got it.Thanks

You cant take input of all characters from cin>>c,because cin ignores characters like space and enter.

Try this! you Can read Tab,Space and enter etc.

#include<iostream>
using namespace std;
int main()
{
char c,n;
cin.get(c);
cout<<int(c)<<endl;
return 0;
}