C :将文本文件的内容存储在2D数组中,作为字符串(用于NULL终结器的麻烦?)

C++: Store contents of text file into 2D array as strings (trouble with null terminator?)

本文关键字:NULL 用于 字符串 麻烦 文件 文本 存储 数组 2D      更新时间:2023-10-16

我正在使用数组和文件阅读以尝试更深入地了解它们,因此,如果我对此提出很多问题,我深表歉意。

我当前有一个程序,该程序应该从文件中读取字符,然后将这些字符串作为字符串存储到2D数组中。例如,此文件包含一个标题号和名称列表:

5
Billy
Joe
Sally
Sarah
Jeff

因此,在这种情况下,2D数组将具有5行和x列数(每个名称一行)。该程序一次读取文件一个字符。我认为我遇到的问题实际上是在每行末尾插入无效终结器,以表明这是该字符串的终点,但是总的来说,我不确定怎么了。这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
const int MAX_NAME_LENGTH = 50;
void printNames(char [][MAX_NAME_LENGTH + 1], int);
int main(void)
{
    ifstream inputFile;
    string filename;
    int headernum, i = 0, j;
    const int MAX_NAMES = 10;
    char ch;
    char names[1][MAX_NAME_LENGTH + 1];
    cout << "Please enter the name of your input file: ";
    cin >> filename;
    inputFile.open(filename.c_str());
    if (inputFile.fail())
    {
        cout << "Input file could not be opened. Try again." << endl;
    }
    inputFile >> headernum;
    if (headernum > MAX_NAMES)
    {
        cout << "Maximum number of names cannot exceed " << MAX_NAMES << ". Please try again." << endl;
        exit(0);
    }
    inputFile.get(ch);
    while (!inputFile.eof())
    {
        for (i = 0; i < headernum; i++)
        {
            for (j = 0; j < MAX_NAME_LENGTH; j++)
            {
                if (ch == ' ' || ch == 'n')
                {
                    names[i][j] = '';
                }
                else
                {
                    names[i][j] = ch;
                }
            }
        }
        inputFile.get(ch);
    }
    cout << names[0] << endl;
    //printNames(names, headernum);
    return 0;
}
void printNames(char fnames[][MAX_NAME_LENGTH + 1], int fheadernum)
{
    int i;
    for (i = 0; i < fheadernum; i++)
    {
        cout << fnames[i] << endl;
    }
}

它编译,这是输出:http://puu.sh/7pyxv.png

显然这里有些错误!我倾向于说特定的问题在于我的if(ch =''等)陈述,但我敢肯定,这可能远不止于此。我只是在弄清楚问题所在的位置时遇到了麻烦。与往常一样,帮助和/或指导非常感谢!

现在您对初始代码有一些反馈。这是做到这一点的一种简单的方法(还有更多的C ):

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char **argv)
{
  ifstream inputFile;
  string filename;
  cout << "Please enter the name of your input file: ";
  cin >> filename;
  inputFile.open(filename.c_str());
  if (inputFile.fail())
  {
      cout << "Input file could not be opened. Try again." << endl;
      return 1;
  }
  int headerNum = 0;
  inputFile >> headerNum;
  if(inputFile.eof()) {
      cout << "Error reading input file contents." << endl;
      return 1;
  }
  string *names = new string[headerNum];
  for(int i = 0; i < headerNum; i++)
    inputFile >> names[i];
  for(int i = 0; i < headerNum; i++)
    cout << names[i] << endl;
}