【发布时间】:2015-02-12 23:21:23
【问题描述】:
我正在开发一个程序,该程序应该从文件中读取并将该文件的内容存储在向量中。我必须读取 .txt 文件的内容并将字符串推回向量中,然后才能到达“”。如果它是一个空格,您将跳过文件的该部分并继续在空格后面推回内容。有谁知道使用什么函数从文件中读取并将内容放入向量或数组中?谢谢你的时间。
int main()
{
Code mess;
ifstream inFile;
inFile.open("message1.txt");
if (inFile.fail()) {
cerr << "Could not find file" << endl;
}
vector<string> code;
string S;
while (inFile.good()) {
code.push_back(S);
}
cout << mess.decode(code) << endl;
return 0;
}
【问题讨论】:
-
您将需要使用 fopen、fgets、fclose。请务必在您提出下一个问题之前发布您的代码。
-
将问题分解为多个部分,不用担心存储在向量或数组中,只需读取文件并输出字符串即可。提示:使用 cin 或 fgets(如 Mike 所说)
-
while (inFile.good())应该是while(inFile >> s),这样就可以了。 -
请搜索 StackOverflow 以获取将文件读入数组的示例:Examples of reading into vector