Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ &引用;字符串下标超出范围“;使用向量时出错_C++_String_Vector - Fatal编程技术网

C++ &引用;字符串下标超出范围“;使用向量时出错

C++ &引用;字符串下标超出范围“;使用向量时出错,c++,string,vector,C++,String,Vector,我试图从文本文件的特定列(在本例中为0)中提取字符,并将它们加载到向量中。代码似乎工作正常,直到最后出现“字符串下标超出范围”错误,我不知道如何修复该错误。有人知道我能做什么吗?这是相关代码 class DTree { private: fstream newList; vector<string> classes; public: DTree(); ~DTree(); void loadAttributes(); }; void DTree:

我试图从文本文件的特定列(在本例中为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);
}
}
类数据树
{
私人:
fstream新列表;
向量类;
公众:
DTree();
~DTree();
void loadAttributes();
};
void DTree::loadAttributes()
{ 
字符串行=”;
打开(“newList.txt”);
字符串属性=”;
while(newList.good())
{
getline(newList,line);
属性=行[0];
类。推回(属性);
}
}
请尝试
'while(getline(newList,line)

参考请尝试
'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)

您也可以尝试类似的方法

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)

您确定
line
读取正常吗?如果是,您如何确定?
line
必须为空(size()==0),您的文件是否以空行开头?读取到第一行“\n”或新行character@KarthikT,您的意思是一个空行,但想法相同。我同意chris的观点,在访问行[index]之前,您应该检查line.size()>index。只需在(getline)(newList,line)时重试不检查“good”是否确实读取了
是否正常?如果是,您如何确定?
必须为空(size()==0),您的文件是否以空行开始?读取到第一行“\n”或新行character@KarthikT,你的意思是空行,但想法相同。我同意克里斯的观点,你应该检查行。大小()>在访问行[index]之前进行索引。只需在(getline(newList,line))时尝试,而不是检查“good”