-4

The problem with my code is that it never gets into the if. In other words it never reads the '\n' character. The '\n' exists in the file I want to read and it is important to read it in order to save the matrix the right way.

#include <iostream>
#include <cstring>
#include <fstream>
#include <iomanip>
using namespace std;


int main(int argc, char **argv){

  int N, M;
  int n, m;
  int i, j;
  char a;
  ifstream myfile;
  string txt;
  char mat[1000][1000];

  txt = argv[1];
  myfile.open(txt);

  n = 0;
  m = 0;
  while(myfile >> a){
    if(a == '\n'){
      n++;
      m = 0;
      continue;
    }

      mat[n][m] = a;
      m++;
  }

  myfile.close();
  cout << n << " " << m;
  for(i=0; i<=n; i++){
    cout << endl;
    for(j=0; j<m; j++){
      cout << mat[i][j] << " ";
    }
  }
}
puzzle
  • 5,881
  • 1
  • 22
  • 30
billyntua
  • 1
  • 2
  • 1
    Maybe your file does not contain any newlines? We can't really help without a [mcve] + some example input data. – Jesper Juhl Apr 14 '19 at 14:13
  • 2
    What is the type of `a`? Please post some compilable code. –  Apr 14 '19 at 14:14
  • edited guys I'm sorry new here – billyntua Apr 14 '19 at 15:47
  • Rather than post everything, post a complete program that does only the minimum required to demonstrate the problem. A simple solution to your problem is outlined in Option 2 in [this linked answer](https://stackoverflow.com/a/7868998/4581301). – user4581301 Apr 14 '19 at 16:18
  • `myfile >> a` skips whitespace. It appears you want to get a character at a time, and not skip whitespace. The operator `>>` streaming is the wrong thing to use for this situation. Use this: http://www.cplusplus.com/reference/istream/istream/get/ – Eljay Apr 14 '19 at 19:32

1 Answers1

-1

There are two equivalent functions for entering a character — getc () and fgetc (). Support two identical functions

The getc() function is used to read characters from a stream opened for reading with fopen(). The getc() prototype is as follows:

int getc(FILE * fp);

where fp is a pointer to a file type FILE * returned by fopen(). Traditionally, getc() returns an integer, but the high byte is set to 0.

The getc() function returns EOF when the end of the file is reached. To read the text file to the end, use the following code:

ch = getc(fp);
while (ch! = EOF) 
{
  enter code here`ch = getc (fp);
}

Or you can try

if(a == '\')
bogdyname
  • 198
  • 1
  • 8