在將文件abc.txt叫,我有輸入以下文本:C++矢量subsctript超出範圍
sample text
sample text
sample text
sample text
sample text
首先我創建的變量(名稱爲文本),用於保存文本的從文件中讀取。然後程序讀取文件abc.txt。我創建了名爲ArrSent的矢量,用於保存文件abc.txt中的每一行。循環結束後,程序關閉文件abc.txt。然後程序必須輸出ArrSent中的所有句子給screnn。我有這樣的問題:程序結束後,出現警告消息:vector下標超出範圍。我不知道爲什麼..
#include<iostream>
#include<string>
#include<fstream>
#include<vector>
using namespace std;
void function()
{
string text;//variable to save text from file
ifstream myfile("abc.txt");//reading from file colled abc.txt
vector<string> ArrSent;
if (myfile.is_open())
{
//cout <<"myplik.good()= "<< myfile.good() << endl;
while (myfile.good())
{
getline(myfile, text);
ArrSent.push_back(text);
}
myfile.close();
}
for (int i = 0; i <= ArrSent.size(); i++)
{
cout << ArrSent[i] << endl;
}
}
int main()
{
function();
system("pause");
return 0;
}
'is_open()'和'good()'是完全沒有意義的,而'getline'後面的'push_back'是平坦的,因爲你忽略了返回值。 – 2014-10-08 21:18:29
請擺脫[系統(「暫停」)](http://www.gidnetwork.com/b-61.html) - 它是危險的和不可移植的。 – 2014-10-08 21:22:51