C++ 试图将文本文件中的单词添加到向量中,但不断抛出';std::超出范围';
试图添加此文本文件中的单词,但不断抛出超出范围的错误。我认为错误在于循环中的某些地方,但是我还没有弄清楚为什么它不工作。非常感谢您的帮助C++ 试图将文本文件中的单词添加到向量中,但不断抛出';std::超出范围';,c++,vector,fstream,C++,Vector,Fstream,试图添加此文本文件中的单词,但不断抛出超出范围的错误。我认为错误在于循环中的某些地方,但是我还没有弄清楚为什么它不工作。非常感谢您的帮助 #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; struct WordCount{ string word; int count; }; int ma
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct WordCount{
string word;
int count;
};
int main () {
vector<WordCount> eggsHam;
ifstream readFile ("NewTextDocument.txt");
int counter = 0;
int holder;
string lineRead;
WordCount word;
if(readFile.is_open()){
//add all the words into a vector
while (getline(readFile, lineRead)){
holder = counter;
for(int i = 0; i < lineRead.length(); ++i) {
if (lineRead.at(i) != ' ') {
++counter;
}
if (lineRead.at(i) != ' ') {
for (int k = 0; k < (counter - holder); ++k) {
word.word.at(k) = lineRead.at(holder + k);
}
eggsHam.push_back(word);
++counter;
}
}
}
readFile.close();
}
else cout << "Unable to open file";
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
结构字数{
字符串字;
整数计数;
};
int main(){
向量eggsHam;
ifstream readFile(“NewTextDocument.txt”);
int计数器=0;
int持有人;
字符串行读取;
字数字;
if(readFile.is_open()){
//将所有单词添加到向量中
while(getline(readFile,lineRead)){
支架=计数器;
对于(int i=0;i 否则你的代码就太复杂了。要将所有单词(=空格分隔的东西)读入一个std::vector
,只需执行以下操作:
#include <cstdlib>
#include <vector>
#include <string>
#include <iterator>
#include <fstream>
#include <iostream>
int main()
{
char const *filename = "test.txt";
std::ifstream is{ filename };
if (!is.is_open()) {
std::cerr << "Couldn't open \"" << filename << "\" for reading :(\n\n";
return EXIT_FAILURE;
}
std::vector<std::string> words{ std::istream_iterator<std::string>{ is },
std::istream_iterator<std::string>{} };
for (auto const &w : words)
std::cout << w << '\n';
}
#包括
#包括
#包括
#包括
#包括
#包括
int main()
{
char const*filename=“test.txt”;
std::ifstream是{filename};
如果(!is.is_open()){
std::cerr哪一行抛出错误?在使用at
函数之前,应该调整word.word的大小。尝试在循环之前添加word.word.resize(计数器保持器)
。