In c++, ascii characters has a default value. Like ! has a value of 33, "," has also a value of 44 and so on.
inside my text file "hehe.txt" is. ;!,.
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("hehe.txt");
if(file.eof())
return 0;
char ascii;
while(file>>ascii) {
std::cout << (int)ascii << " ";
}
system("pause");
}
Output is 59 33 44 46
.
Edit: How may I prevent space to be ignored as being read from the text file when I run my program? Suppose I added space after the last character ;!,.
thus, the output must be 59 33 44 46 32
. Hope someone could give me an idea how to do it.
The problem is the separator. When you use file >> ascii
this will "eat" all your spaces as these are used as separators.
You can use getline
and then iterate over all chars in the string.
std::ifstream file("../../temp.txt");
if(!file)return 0;
std::string line;
while (std::getline(file, line, '\0')){
for(char ascii : line){
std::cout<<(int)ascii << " ";
}
}
system("pause");
return 0;
What is also possible, as dornhege says, is:
while(file >> std::noskipws >> ascii){
std::cout << (int) ascii << "\n";
}
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