循环在将数据从文件读取到数组C++时跳过行
Loop skips lines when reading data from a file into array C++
我正在为我的 CS 1 类做一个项目,我们必须创建一个将数据从文件读取到数组中的函数。但是,当它运行时,它只读取每隔一行数据。
该文件包含 22 3 14 8 12 和我得到的输出:3 8 12
任何帮助都非常感谢。抱歉,如果这已经得到回答,我找不到它。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int readin();
int main() {
readin();
return 0;
}
int readin(){
ifstream inFile;
int n = 0;
int arr[200];
inFile.open("data.txt");
while(inFile >> arr[n]){
inFile >> arr[n];
n++;
}
inFile.close();
for(int i = 0; i < n; i++){
cout << arr[i] << " " << endl;
}
}
原因是您在条件查询中从文件流中读取:
while(inFile >> arr[n]) // reads the first element in the file
然后再次读取它并在循环中重写此值:
{
inFile >> arr[n]; // reads the next element in the file, puts it in the same place
n++;
}
只需做:
while(inFile >> arr[n]) n++;
你可以简单地这样做:
while(inFile >> arr[n]){
n++;
}
但是,如果文件中的值数大于数组大小怎么办?那么你面临着一个undefined behavior
.
我建议使用
vectors
:std::vector<int> vecInt; int value; while(inFile >> value) vecInt.push_back(value); for(int i(0); i < vecInt.size(); i++) std::cout << vecInt[i] << std::endl;
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '