如何将文件从文件读取到数组中
How to Read Lines From a File Into an Array
我试图使用Fstream将文件从文件中读取到数组中,然后将它们打印出来。我尝试通过使用for loop和a Getline命令来执行此操作,但是该程序一直在崩溃,并给我"抛出:写访问违规"消息。我应该在程序中修复某些问题,还是有更好的方法来执行此操作?
文件文本:
Fred Smith 21
Tuyet Nguyen 18
Joseph Anderson 23
Annie Nelson 19
Julie Wong 17
代码:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
cout << "Harrison Dong - 7/21/17" << endl;
string fileStuffs[4];
ifstream fin;
fin.open("C:\Users\Administrator\Documents\Summer 2017 CIS 118-Intro
to Comp. Sci\Module 17\firstLastAge.txt");
if (!fin.is_open()) {
cout << "Failure" << endl;
}
for (int i = 0; i < 5 && !fin.eof(); i++) {
getline(fin, fileStuffs[i]);
cout << fileStuffs[i] << endl;
}
fin.close();
system("Pause");
return 0;
}
谢谢!
有更好的方法吗?
是。使用std :: vector。
#include <iostream>
#include <fstream>
#include <string>
#include <vector> // added to get vector
int main() {
using namespace std; // moved to restrict scope to a place I know is safe.
cout << "Bill Pratt - 7/21/17" << endl; // changed name
vector<string> fileStuffs; // vector is a smart array. See documentation link
// above to see how smart
ifstream fin("C:\Users\Administrator\Documents\Summer 2017 CIS 118-Intro to Comp. Sci\Module 17\firstLastAge.txt");
if (!fin.is_open()) {
cout << "Failure" << endl;
}
else // added else because why continue if open failed?
{
string temp;
while (getline(fin, temp)) // reads into temporary and tests that read succeeded.
{
fileStuffs.push_back(temp); // automatically resizes vector if too many elements
cout << fileStuffs.back() << endl;
}
}
// fin.close(); file automatically closes on stream destruction
return 0;
}
相关文章:
- 如何将内容数组写入文本文件?
- C++将文本文件中的数据读取到结构数组中
- 将值从二维数组输出到文本文件
- C++数据文件、数组和计算赋值
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何从txt文件中读取多个不同长度的数组?
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- C++编程从外部文本文件定义数组大小
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 将系数存储在头文件的数组中("does not name a type"错误)
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 从文件读取,并写入函数C++中的数组
- 如何使用QJSONARRAY在QT5(C )中解析JSON文件(数组)
- 从文件/数组C++聚合数据