C ++:将文本文件的内容作为字符串存储到2D数组中(使用null终止符?)

时间:2014-03-10 00:41:24

标签: c++ multidimensional-array c-strings

我正在使用数组和从文件中读取更多内容以尝试更深入地了解它们,所以如果我就此提出很多问题,我会道歉。

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

5
Billy
Joe
Sally
Sarah
Jeff

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

#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] = '\0';
                }

                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 =''etc)语句,但它可能远不止于此,我敢肯定。我只是弄清楚问题所在。一如既往,非常感谢帮助和/或指导!

1 个答案:

答案 0 :(得分:1)

现在您对初始代码有了一些反馈。这是一个更简单的方法(和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;

}