gpt4 book ai didi

C++:将文本文件的内容作为字符串存储到二维数组中(空终止符有问题吗?)

转载 作者:行者123 更新时间:2023-11-28 07:02:04 26 4
gpt4 key购买 nike

我更多地使用数组和读取文件来尝试更深入地了解它们,所以如果我问了很多关于这方面的问题,我深表歉意。

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

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;

}

关于C++:将文本文件的内容作为字符串存储到二维数组中(空终止符有问题吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22290269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com