初始化文本文件中的向量 [英] Initializing a vector from a text file
问题描述
我正在尝试编写一个程序,该程序可以在文本文件中读取,并将其中的每个单词作为字符串类型向量中的条目存储.我确定我做错了,但是自从尝试这样做以来已经很久了,以至于我忘记了它是如何完成的.任何帮助是极大的赞赏.预先感谢.
I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
推荐答案
许多可能的方法之一是简单的:
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
运算符>>>
仅处理被读取的单词,该单词除以空格(包括换行符)而被读取.
operator >>
takes care of only words divided by whitespaces (including new-lines) being read.
如果要按行读取它,则可能还需要显式处理空行:
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
这篇关于初始化文本文件中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!