[英]Reading integers and strings from a text file and storing in parallel arrays
[英]Storing and Reading Strings From Arrays
我正在為分配執行的某些代碼有問題。 當我去編譯文件時,它有時可以工作,有時則不能。 該程序的基本思想是從文件中讀取每一行文本並將其存儲到一個數組中(該數組的大小應為100,而文本行應為100)。 每個文本字符串(每行)應存儲在其自己的數組地址中。 一旦存儲了所有行,程序將從數組中拉出每一行,並注意它來自哪一行。 當使用Code :: Blocks進行編譯時,它沒有問題,但是,當我使用cygwin進行編譯時,我去運行它並收到一條錯誤消息,內容為:“在拋出'std :: bad_cast'實例后終止調用了什么( ):std :: bad_cast中止(核心已轉儲)“
你們能給我的任何幫助將不勝感激!
這是到目前為止我得到的代碼:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
string aFile[100];
ifstream nFile("TMA1Question4 Text.txt");
string nText;
if (nFile)
{
for (int nLineCounter=1; nLineCounter <=100; getline(nFile, nText))
{
aFile [nLineCounter] = nText;
nLineCounter++;
}
}
for (int nLineReader=1; nLineReader<=100; nLineReader++)
{
cout << "Line" << nLineReader << ": " << aFile[nLineReader] << endl;
}
return 0;
}
首先,陣列被從0索引你的數組的索引范圍是從0到99,而不是從1到100個。你for
環路應該看起來更像:
for (int nLineReader=0; nLineReader<100; nLineReader++)
您嘗試以偷偷摸摸的方式使用for
循環也是一個問題。 該getline
將只在每次迭代之后調用。 在第一次迭代中,您將空字符串nText
到數組中。 更改為:
for (int nLineCounter=0; nLineCounter<100; nLineCounter++)
{
getline(nFile, nText);
aFile [nLineCounter] = nText;
}
當然,這取決於您確定文件中有100行。 從文件讀取行的更安全方法是將getline
用作循環的條件:
int nLineCounter = 0;
while (getline(nFile, nText))
{
aFile[nLineCounter] = nText;
nLineCounter++;
}
但是,如果要使用標准容器(應該使用),則可以從文件中讀取所有行而根本沒有循環 。
C和C ++中的索引是從零開始的 ,因此您的計數器應從0開始,並比max少1
就是說,考慮使用std::vector
而不是原始數組。 然后,您可以使用std::vector
的push_back
方法。 這樣,您可以更輕松地存儲任意數量的行,而不僅僅是100條。
當前代碼還存在其他一些問題,但是當您修復技術問題后,大概會發現並修復所有問題…;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.