![](/img/trans.png)
[英]C++ How to store numbers in a text file with contents of characters , numbers , and comma delimited in a 2D matrix
[英]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.