如何从文件中读取“”字符

How to read from a file the ' ' character

本文关键字:字符 读取 文件      更新时间:2023-10-16

我的代码的问题在于它永远不会进入if。换句话说,它从不读取""字符。""存在于我要读取的文件中,这很重要读取它以便以正确的方式保存矩阵。

#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] << " ";
    }
  }
}

输入字符有两个等效的函数 — getc ()fgetc () 。支持两个相同的功能

getc() 函数用于从打开的流中读取字符 fopen() .getc()原型如下:

int getc(FILE * fp);

其中 fp 是指向 fopen() 返回的文件类型 FILE * 的指针。传统上,getc()返回一个整数,但高字节设置为 0。

getc()函数在到达文件末尾时返回 EOF。若要将文本文件读到最后,请使用以下代码:

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

或者你可以试试

if(a == '')