[英]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.