[英]putting a list (.txt) file into a 2D array
我正在尝试分离一个文本文件(具有200个字符串的列表),并将每个其他字符串(列表中的偶数和奇数)存储到2D数组中。
文本文件以这种方式排序(没有数字):
我想将其存储在一个称为strLine [101] [2]的二维数组中,以便对其进行遍历,以便列表中的第一个字符串位于位置[0] [0],列表的第二个字符串位于位置[0] [1],依此类推,直到文件读完并且列表变成这样(没有数字)为止为止:
我的代码目前输出原始的未排序列表,我想知道如何实现2d数组(使用正确的语法)以及如何在getline()函数中实现i,j for循环,以便它可以迭代每个2D数组的元素。
任何帮助将不胜感激。
我的代码:
bool LoadListBox()
{
// Declarations
ifstream fInput; // file handle
string strLine[201]; // array of string to hold file data
int index = 0; // index of StrLine array
TCHAR szOutput[50]; // output to listbox,
50 char TCHAR
// File Open Process
fInput.open("data.txt"); // opens the file for read only
if (fInput.is_open())
{
getline( // read a line from the file
fInput, // handle of file to read
strLine[index]); // storage destination and index iterator
while (fInput.good()) // while loop for open file
{
getline( // read line from data file
fInput, // file handle to read
strLine[index++]); // storage destination
}
fInput.close(); // close the file
index = 0; // resets back to start of string
while (strLine[index] != "") // while loop for string not void
{
size_t pReturnValue; // return code for mbstowcs_s
mbstowcs_s( // converts string to TCHAR
&pReturnValue, // return value
szOutput, // destination of the TCHAR
50, // size of the destination TCHAR
strLine[index].c_str(), // source of string as char
50); // max # of chars to copy
SendMessage( // message to a control
hWnd_ListBox, // handle to listbox
LB_ADDSTRING, // append string to listbox
NULL, // window parameter not used
LPARAM(szOutput)); // TCHAR to add
index++; // next element of string array
}
return true; // file loaded okay
}
return false; // file did not load okay
}
转换string strLine[201];
string place[100][2];
到string place[100][2];
。 还可以考虑制作一个
struct place
{
std::string state;
std::string city;
};
因为它更确切地存储了什么。 更具表现力的代码更易于阅读,通常可以防止错误(更难于偶然使用strLine[x][2]
或类似的东西),并且需要更少的注释。 注释本身的代码应该是个人目标。 编译器当然不在乎,但是很少有人是编译器。
使用两个单独的index
变量。 将第一个名称命名为num_entries
因为它实际上是在计算数组中的项目数。
将两行读入内部数组并测试读取结果。 如果他们读取成功,则增加index
。
while (getline(fInput, place[num_entries][0]) && getline(fInput, place[num_entries][1]))
{
num_entries++;
}
步骤2将while (strLine[index] != "")
转换为while (index < num_entries)
用一个常数替换所有的50
s。 这样,您就无法更改值并且错过了50
s的时间,并且比原始数字更容易从一个好的描述性标识符中推断出含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.