Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a space character from a text file in c++ [closed]

Tags:

c++

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.

like image 462
kersey Avatar asked Feb 16 '23 06:02

kersey


1 Answers

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";
  }
like image 117
RedX Avatar answered Mar 03 '23 15:03

RedX