繁体   English   中英

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

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

我正在处理数组并从文件中读取内容,以尝试更深入地了解它们,因此,如果我提出很多与此有关的问题,我深表歉意。

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

5
Billy
Joe
Sally
Sarah
Jeff

因此,在这种情况下,二维数组将具有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] = '\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)语句,但是我敢肯定,这可能不止于此。 我只是很难找出问题所在。 一如既往,非常感谢您的帮助和/或指导!

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM