Search code examples
c++charswitch-statementdo-whilefile-read

How to read spaces as characters in C++


I want to read all characters from a .txt file, but my program is not reading the spaces and I don't know why. I also want to test all characters with a switch, but spaces are not detected as characters. How to solve this problem?

PS: I want to solve this without getline

Here is my code:

#include <iostream>
#include <fstream>
#define InFile "intra.txt"
#define OutFile "raspuns.txt"
using namespace std;
ifstream fin(InFile);
ofstream fout(OutFile);

int main()
{
long int i,valori[100],aux, contor;
char a[10000];


i=0;
contor = -1;
do
{
 contor++;
 i++;
 fin>>a[i];
 cout<<a[i]<<"\n";
 switch(a[i]){
 ...
 }

Solution

  • Try like this

    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;