c++ - 从文件数据c ++分配数组
问题描述
这是我的代码,其中 prime.txt 包含一些素数:7、11、13、17、23...:
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string file= "primes.txt";
ifstream fichier;
fichier.open(file);
int count = 0, prime;
int *buffer = (int*) malloc(8080*sizeof(int));
while ( fichier >> prime){
buffer[count] = prime;
count++;
}
fichier.close();
return 0;
}
我想知道是否有一种方法可以在不使用循环的情况下从文件数据中分配一个数组?我看到你可以用二进制文件来做,但我想知道我们是否也可以用 string 或 int 来做文件。
解决方案
这是一个不使用显式循环的方法:
fichier >> buffer[count++]; // Read and convert to internal format
fichier >> buffer[count++];
fichier >> buffer[count++];
// Repeat for each number in the file
fichier >> buffer[count++];
在运行时库中,读取字符时使用循环来构建数字。此外,输入流可能会被缓冲,这是另一个循环。
推荐阅读
- python - 针对以下问题的 numpy 数组的迭代
- html - 不同的 CSS 样式行为取决于图像样式
- java - RecyclerView 未加载所有项目
- swift - XCTest 类 func setUp() 方法如何处理失败
- php - 如何在 PHP 中将字符串拆分/分解为编号列表?
- reactjs - React Native Navigation 5.0 bottomTabs - 如何更改字体大小?
- python-2.7 - Python 代码无法在 RPi 上编译(缺少 lib-old 文件夹)
- java - 将文本文件内容转换为矢量元素
- android - 更新 Android Facebook 登录时出现问题
- javascript - 如何在 TypeScript 中将函数类型声明为参数