将整数从文本文件插入到整数数组
Inserting integers from a text file to an integer array
我有一个装有一些整数的文本文件,我想将这些数字插入此文本文件中的整数数组。
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream file("numbers.txt");
int nums[1000];
if(file.is_open()){
for(int i = 0; i < 1000; ++i)
{
file >> nums[i];
}
}
return 0;
}
,我的文本文件包含按行逐行的整数,例如:
102
220
22
123
68
当我尝试使用单个循环打印数组时,除文本文件中的整数外,它还打印许多" 0"。
始终检查文本格式提取的结果:
if(!(file >> insertion[i])) {
std::cout "Error in file.n";
}
可能是您的文本文件不包含1000个数字吗?
我建议使用std::vector<int>
代替固定尺寸的数组:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(){
ifstream file("numbers.txt");
std::vector<int> nums;
if(file.is_open()){
int num;
while(file >> num) {
nums.push_back(num);
}
}
for(auto num : nums) {
std::cout << num << " ";
}
return 0;
}
相关文章:
- 从二进制文件中读取整数数组
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 从两个 4x64 位整数数组中获取取模
- 字符到整数数组
- 从函数参数 [C++] 复制整数数组
- 指向整数数组和打印总和的指针
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 线程安全整数数组?
- 整数数组中最长的回文
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- 创建<int>对整数数组指针的矢量引用 (C++)
- 整数指针数组的元素是否可以指向整数数组?
- 如何将整数数组相乘得到一个数字?
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 将文本文件读入整数数组