【问题标题】:How to read a .txt file using c-strings?如何使用 c-strings 读取 .txt 文件?
【发布时间】:2016-09-08 01:19:54
【问题描述】:

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

听起来很容易,但我的教授对项目进行了限制:NO STRINGS ("不允许使用字符串数据类型或字符串库。")

我一直在使用 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(不是 char 数组)。

感谢任何帮助!

【问题讨论】:

  • 如果遇到NO STRINGS,只是一个空字符串“”,或者除了exit什么都没有,你需要什么结果?
  • @vinllen 我将在这里引用规则:“不允许使用字符串数据类型或字符串库。”
  • 如果您的讲师实际上将其全部大写并且没有明确声明您不能使用std::vector,我会使用std::vector。见stackoverflow.com/questions/4761529/…
  • 文本文件包含什么?这很重要,因为如果它包含数字,那么不需要字符串,如果它包含文本,那么应该使用 char*

标签: c++ arrays char fstream ifstream


【解决方案1】:

使用cin.getline。格式参考本站:cin.getline

你可以这样写:

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

【讨论】:

    【解决方案2】:

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

    get() 返回后,使用gcount() 方法确定读取了多少个字符。

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

    【讨论】:

      【解决方案3】:

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

      您还可以使用 while(cin.getline()) 以 C++ 样式读取每个循环的每行: istream&amp; 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]);
          }    
      }
      

      【讨论】:

      • istream&amp; getline (char* s, streamsize n, char delim ); 究竟会去哪里?我有点困惑
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      相关资源
      最近更新 更多