如何使用 C 字符串读取 .txt 文件?

How to read a .txt file using c-strings?

我正在为学校做一个项目,我需要从文件中读取文本。

听起来很简单,除了我的教授对项目施加了限制:NO STRINGS ("No string data types or the string library are allowed.")

我一直在使用 char 数组解决这个问题;但是,我不确定如何使用 char 数组从文件中读入。


这是来自另一个网站的示例,关于如何读取文件字符串。

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

这里重要的一行是while ( getline (myfile,line) );

getline 接受一个 ifstream 和一个 string(不是字符数组)。

感谢任何帮助!

ifstream 有一个名为 get() 的方法,它将文件的内容读入 char 数组。 get() 将指向数组的指针和数组的大小作为参数;如果可能的话,将数组填充到给定的大小。

get()returns后,用gcount()方法判断读了多少个字符

您可以使用 then 和一个简单的逻辑循环,以 size 块的形式重复读取文件内容到一个数组中,并将读取的所有块收集到一个数组中,或者std::vector.

使用cin.getline。请参阅此站点的格式:cin.getline.

你可以这样写:

ifstream x("example.txt");
char arr[105];
while (x.getline(arr,100,'\n')){
    cout << arr << '\n';
}

可以使用int i = 0; while (scanf("%c", &str[i ++]) != EOF)判断文本输入结束。 str 是你想要的包含换行符的字符数组,i 是输入大小。

您还可以使用 while(cin.getline()) 以 C++ 样式逐行读取每个循环: istream& getline (char* s, streamsize n, char delim ); 如下所示:

const int SIZE = 100;
const int MSIZE = 100;
int main() {
    freopen("in.txt", "r", stdin);
    char str[SIZE][MSIZE];
    int i = -1;
    while (cin.getline(str[++ i], MSIZE)) {
        printf("input string is [%s]\n", str[i]);
    }    
}