2016-03-21 16 views
-1

Bir borudan yazmaya ve okumaya çalışırken sorun yaşıyorum. Bir dizi asal sayı oluşturmalı ve bu diziyi borudan okuyacak bir boruya yazmalıyım. Birden çok farklı yolu denedim ama anlayamıyorum.Borulara bir dizi yazma

İşte kodum.

#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <stdlib.h> 
#include <string> 
#include <iostream> 
#include <sstream> 
#include <string.h> 
using namespace std; 

int main(int argc, char *argv[]){ 

int n = 10000; 
int array[n] = {0}; 
int nums[n] = {0}; 
int k = 0; 
int answer[argc] = {0}; 

//this loop makes an array or prime numbers acording to the node 
//if that node number is not a prime number it puts a 0 in that node 
for(int i =2; i < n; i++){ 
    for(int j = (i*i); j < n; j+=i){ 
     array[j-1] = 1; 
    } 
} 
//this loop makes an array of all the prime numbers; 
for(int i = 1; i < n; i++){ 
    if(array[i -1] == 0){ 
     nums[k] = i; 
     k++; 
    } 
} 
//this loop puts the selected prime numbers in the array 
for(int j = 1; j < argc; j++){ 
    int num = atoi(argv[j]); 
    answer[j - 1] = nums[num]; 
} 
//this loop prints the primes for testing 
for(int i = 1; i < argc; i++) 
    cout << answer[i - 1] << endl; 


int fd[2], nbytes; 
pid_t childpid; 
string number; 
int readbuffer[90]; 
string numbers; 
pipe(fd); 

if((childpid = fork()) == -1){ 
    perror("fork"); 
    exit(1); 
} 

if(childpid == 0){ 

    close(fd[0]); 
    for(int i = 0; i < argc; i ++){ 

    write(fd[1], &answer[i], sizeof(int)); 
    } 
    exit(0); 
} 

else{ 
    close(fd[1]); 
    for(int i = 0; i < argc; i++){ 
     nbytes = read(fd[0], readbuffer, sizeof(int)); 
     printf("recieved string: %s", readbuffer); 
    } 
} 

}

+0

Not: son iki 'for' döngüsünün' i user3386109

cevap

1

Sen int bayt kodlama

write(fd[1], &answer[i], sizeof(int)) 

doğru
nbytes = read(fd[0], readbuffer, sizeof(int)) 

onları okumak ama C-dizeleri olarak bunları yazdırmak için deneyin değerleri yazma

printf("recieved string: %s", readbuffer) 

Derleyiciniz burada yanlış türden şikayetçi olmalıdır. Değiştirin

printf("...%d\n",*readbuffer); 

Kodunuz C++ iken C akışlarını kullandığınızdan emin olun. C++ - stream kullanmak daha iyi olacaktır ...