从文本文件中读取尺寸和表格内容后显示表格

Display a table after reading in dimensions and table contents from a text file

本文关键字:表格 显示 文件 文本 读取      更新时间:2023-10-16

我目前正在处理一个项目,该项目在从文本文件中读取表的内容和维度后显示表。

puzzle.txt的内容:

5 5
ferac
asdvb
mfkgt
opemd
welsr

我希望我的程序读取左边的数字并将其存储在变量numRow中,右边的数字存储在numCol中,然后将字母读取到谜题数组中。然而,当维度数字打印时,它们打印为0 0而不是5 5,并且益智数组只输出空框字符。

#include <iostream>
#include <map>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
char puzzle [numRow][numCol];
void initializePuzzle() {
string storeInput;
int numRow, numCol;
cout << "What is the name of the file?" << endl;
getline(cin, storeInput);
ifstream inFile (storeInput);
inFile.open(storeInput.c_str());
for (int c = 0; c < sizeof(storeInput); c++) {
if (c == 0) {
inFile >> numRow >> numCol;
cout << numRow << ' ' << numCol << endl;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
inFile >> puzzle[i][j];
}
}
}
void displayPuzzle() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cout << puzzle[i][j];
}
cout << endl;
}
}
int main() {
initializePuzzle();
displayPuzzle();
return 0;
}

您只需使用C++标准库就可以做到这一点试试这个:(请参阅关于std::copy()std::arraystd::vector…)

#include <iostream>  // For std::cout, std::endl, etc.
#include <fstream>   // For std::ifstream
#include <vector>    // For std::vector
#include <iterator>  // For std::ostream_iterator
int main() {
std::string file_src;
// Ask for file name...
std::cout << "What is the name of the file? " << std::endl;
std::getline(std::cin, file_src);
// Declare the file stream...
std::fstream reader(file_src);
// Terminate the program with value '1' in case of failure when reading file...
if (reader.fail()) return 1;
// Declaring necessary varibles...
unsigned num_row, num_column;
std::string temporary;
/* Extracting 'num_row' and 'num_column' and declaring a 'std::vector' (which are
better than dynamic arrays in numerous ways) with the dimensions... */
reader >> num_row >> num_column;
std::vector<std::vector<char>> puzzle(num_row, std::vector<char>(num_column));
// Iterating over each line and copying the string where required...
for (auto i = 0; std::getline(reader, temporary, 'n') && i < num_row; i++)
if (!temporary.empty())
std::copy(temporary.begin(), temporary.end(), puzzle[i].begin());
else --i;
// Close the stream...
reader.close();
// Print the resulting vector...
for (auto & elem : puzzle) {
std::copy(elem.begin(), elem.end(), std::ostream_iterator<char>(std::cout, " "));
std::cout << std::endl;
}
return 0;
}

示例:

输入

puzzle.txt


输出

f e r a c
a s d v b
m f k g t
o p e m d
w e l s r