c++ - 将数字文件读入向量
问题描述
网上也有类似的问题,但都没有给出充分的答复。我正在尝试使用 ofstream 对象将 3 个随机数写入名为“mydata.txt”的文件,并使用 ifstream 对象从“mydata.txt”中提取这 3 个数字。这是我的代码:
ofstream myOFile {"mydata.txt"}; //open a file using the ofstream default constructor
for(int i = 0; i<3;i++) {
myOFile << (rand() % 100) << "\n"; //write random numbers from 0 to 99 to myOFile
}
ifstream myIFile {"mydata.txt"}; //open the same file using the ifstream default constructor
int nums;
vector<int> numsV;
while(myIFile >> nums) { // myIFile >> nums is false when end of file is reached
numsV.push_back(nums); //add the numbers to a vector of ints called numsV
}
cout << numsV.size() << endl; //Why does this output zero?
for(int i : numsV) {
cout << i << endl; //Why is nothing ouputted here?
}
当我查看计算机上的物理文件 mydata.txt 时,我可以在文档上看到 3 个随机数,这意味着对文件的写入有效。为什么我不能读取文件?
解决方案
推荐阅读
- c# - C# | Listview.Itemssource.orderby(d)
- javascript - 无法理解这个递归示例
- javascript - 在 pyppeteer 中打印 Navigator 属性?
- python - 如何将形状(32,32)的numpy数组存储为(1,32,32)
- javascript - 无法访问对象内的数据 - 菜鸟 Javascript 问题
- mysql - 使用 MySQL JSON_TABLE 将带有未知键的 JSON 扩展到行
- javascript - 获取html表格第一列的值
- html - 反应:网站中的锚标记未在 Safari 中呈现。适用于其他浏览器(Chrome、Edge)
- reactjs - useState 挂钩在页面刷新时丢失地图数据
- python - 将类型 str(带有数字和单词)列转换为 int pandas