簡體   English   中英

向量導致“字符串下標超出范圍”錯誤

[英]“String subscript out of range” error using vectors

我正在嘗試從文本文件的特定列(在本例中為0)中提取字符,並將其加載到向量中。 該代碼似乎可以正常工作,直到到達末尾,當我收到“字符串下標超出范圍”錯誤時,並且我不知道如何解決此問題。 有人知道我能做什么嗎? 這是相關的代碼。

class DTree
{
private:

    fstream newList;
    vector<string> classes;
public:
     DTree();
    ~DTree();

void loadAttributes();
};

void DTree::loadAttributes()
{ 

string line = "";
newList.open("newList.txt");
string attribute = "";
while(newList.good())
{
    getline(newList, line);

    attribute = line[0];
    classes.push_back(attribute);
}
}

請嘗試'while(getline(newList, line)'

請參考這里

您也可以嘗試類似

ifstream ifs("filename",ios::in);

string temp;
getline(ifs,temp)// Called as prime read

while(ifs)
{
    //Do the operations
    // ....

    temp.clear();
    getline(ifs,temp);
}
ifs.clear();
ifs.close();

這適用於幾乎所有類型的文件。您可以根據需要用get()函數或>>運算符替換getline(ifs,temp)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM