首页 > 解决方案 > 从文件数据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 来做文件。

标签: c++file-iomalloc

解决方案


这是一个不使用显式循环的方法:

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++];

在运行时库中,读取字符时使用循环来构建数字。此外,输入流可能会被缓冲,这是另一个循环。


推荐阅读