2012-05-03 4 views
0

저는 C++을 처음 접했을뿐입니다. 나는 올해 학습을 시작했습니다. 텍스트 문서를 가져 와서 배열에 저장하는 작은 프로그램을 작성하는 데 문제가 있습니다. 그 배열을 가져 와서 특정 방식으로 값을 랜덤 화하십시오. 라이더와 말을 적당한 위치에 배치하는 것은 수색 프로그램을위한 것입니다.규칙 집합으로 배열을 셔플하고 함수에서 값 반환

이 함수 (gen())에서 시도하려는 것은 [num2] 항목을 entry2 [num2]에 복사하는 것입니다. 여기서 num은 해당 항목의 양이고 num2는 임의로 생성 된 rand() 번호입니다. 나는 그 다음에 새로운 항목이 적어도 15 자리 이상 (이 경우에는 말의 라이더가 다음 이벤트 전에 휴식을 취할 수 있음)

정도로 추측 할 수 있도록 확인했습니다. 이 응용 프로그램은 작동하지 않습니다, 메신저 쉬운 방법이 있다고 생각하십니까? 변수를이 배열로 보내려면 어떻게해야합니까? 그리고이 함수가 배열을 내 메인으로 되돌릴 수있는 방법은 무엇입니까? 포인터를 통해 추측하고 있습니까?

아래에 전체 코드를 첨부했습니다. - 한, 그 사본을 랜덤 std::random_shuffle를 사용

/* ________________________________________________________________________________ 
* | TITLE:  main.cpp              | 
* | AUTHOR: Samuel Abbott ([email protected])       | 
* | PURPOSE: to take camp draft data in, randomise it with certain values, | 
* |    and output the new roster as a text document     | 
* | DATE:  may 1, 2012              | 
* | LAST EDIT: may 3,2012              | 
* |______________________________________________________________________________| 
*/ 

#include <iostream> 
#include <string> 
#include <stdlib.h> //random number 
#include <time.h> //random number 
#include <fstream> //used for input/output of external files 

using namespace std; 
/* 
* TITLE: gen 
* PURPOSE: to randomise the entries , check to see if they are more then 15 units apart, and return a pointer to the randomised array 
* string entry[] holds original values 
* int num [] holds number of entries 
*/ 
sting gen(string entry[], int num) 
{ 
    int count = 0; 
    string entry2[num]; //randomised array 

    /* initialize random seed: */ 
    srand(time(NULL)); 

    for (count =0; count < num) 
    { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 

     /* a series of if checks to make sure the entry is no less then 15 positions from the previous entry */ 
     if (entry2[num2]=entry[num-15]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-14]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-13]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-12]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-11]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-10]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-9]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-8]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-7]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-6]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-5]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-4]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-3]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-2]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else if (entry2[num2]=entry[num-1]) 
     { 
     num2 = rand() % num; //generate random number 
     entry[num] = entry2[num2]; //copy number from array to a random position in the next array 
     } 

     else 
     { 
     entry[num] = entry2[num2]; 
     } 
    } 

    string pointer* = entry2[] 
    return pointer 
} 

/* 
* Title : Loading 
* Purpose: This function generates a loading animation. in other words. just a fancy  graphic. 
* HAS NO LOADING PURPOSE 
*/ 

void loading() 
{ 
    /* Declare loading variable, this variable is just the screen printout */ 
    string loading = "..."; 
    int time = 0; 
    int loadtime = 10; 

    /* print out loading animation */ 
    while (time != loadtime) 
    { 
     cout << loading; 
     time++; 
    } 

} 
void loading(); 

/* 
* Title: Main 
* Purpose: this is the main function for the randomisation program 
*/ 
int main() 
{ 
//declare all variables 
    string fname = ""; 
    int count; 

    string line; 
    ifstream inputfile; 
    char c; 
    int num=0; 


    /* introduction */ 
    cout << "Roster Randomisation Generator" << endl; 
    /* Get input for roster name */ 
    cout << "Enter a name for the roster, such as 13022012coolah:"<<endl; 
    cin>> fname; 
    /* Begin generating roster */ 
    cout << "Roster Generation in progress." << endl; 
    loading(); 
    /* get amount of lines in text file .. used to determine how many entries there are to  avoid printing blank spaces*/ 

    inputfile.open("output.txt"); 

    while (inputfile.good()) 
    { 
     c = inputfile.get(); 

     if (c=='\n') 
     { 
     num++; 
     } 
    } 

    inputfile.close(); 
    cout<<"Number of Entries counted is: "<<num<<endl; 

    string entry[num]; 

    cout << "Grabbing entries from entry file..."<<endl; 
    /* open text file*/ 
    inputfile.open("output.txt"); 

    /* read all data into the array entry[] */ 
    for (count = 0; count < num; count++) 
    { 
     getline(inputfile,line); //Gets a single line from example.txt 
     entry[count]=line; 

     // inputfile >> entry[count]; 
    } 

    inputfile.close(); 
    cout <<"Found the following entries: " <<endl; 

    /* output captured entries*/ 
    for (count =0; count < num; count++) 
    { 
     cout <<entry[count] <<endl; 
    } 


    return 0; 
} 
+0

다음 질문을 핵심 문제로 줄이십시오. –

답변

2

가장 쉬운 방법은 배열을 복사하는 아마.

2

두 가지 주요 문제가 바로 있습니다.

먼저 gen 함수의 두 번째 줄에 매개 변수 크기의 배열을 만듭니다.

string entry2[num];

당신은 C++에서 정상 "자동"/ 스택 배열이 일정한 크기로 만들 수 있다고 할 수 없습니다.

대신 가변 크기를 가질 수있는 배열을 저장하기 위해 std :: vector를 조사해야합니다. 불필요한 것 같다 다른 문 경우


둘째, 만약 당신의 거대한 사슬이 아니라 버그를 언급.

num2도 잘못되었을 때 어떻게됩니까?

훨씬 적은 코드로이 문제를 해결하려면 for 루프를 사용해야합니다.


세 번째 문제는 if, else if 문의 거대한 체인에서 잘못된 연산자를 사용하고 있다는 것입니다.

비교를 위해 ==을 사용해야합니다. 과제 (=)를 사용하면 효과가있는 것처럼 보일 수 있지만 실제로는 항상 사실을 반환합니다.

+0

그 비교에서'=='의 부족은 말할 것도 없습니다. – chris

+0

또한 모듈러스가있는 rand()를 사용하는 것이 좋지 않다는 점을 추가해야합니다 (바이어스가 있음). http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx 및 http://www.azillionmonkeys.com/qed/random.html 물론 Jerry Coffin의 대답과 같은 것을 사용하면이 문제를 피할 수 있습니다. –

1

먼저 문자열을 반환하고 싶지만 * 함수 정의는 문자열 gen (...)입니다. 그걸 문자열 * gen (...)로 변경하면 좋을 것입니다.

둘째, (entry2 [num2] = entry [num-12]) 인 경우 assays를 수행하고 있습니다. 하지만 당신이 비교하고 싶다고 생각합니다. if (entry2 [num2] == entry [num-12])로 이것을 수행합니다. 비교를 위해 double =과 assaignments를 위해 single =을 사용하십시오.

세 번째로, 복사 및 붙여 넣기를 많이하고 있으며 루프로 캡슐화 할 수 있습니다.

for(int x = 15; x > 0; x--) 
{ 
    if(entry2[num2] == entry[num - x] 
    { 
     num2 = rand() % num; 
     entry[num] = entry[num - x]; 
     break; //maybe ?! 
    } 
} 

네 번째로, 값이 동일한 지 확인한 후에 새 번호를 만드는 이유는 무엇입니까? 어쩌면 당신은 당신의 num2를 잘못한 것이 아니라 비교 후에 유지해야합니다.

다섯 번째로, 내가 올바르게 보았다면 결코 증가 할 수 없습니다. 무한 루프가 발생합니다.

여섯 번째로, [num] 문자열 대신에 새로운 명령문을 사용해야합니다. 이것은 C++에서 작동하지 않습니다.