2012-01-17 11 views
0

これは宿題ですが、それは私のものではありません。私は友人に助けを求めてくれた入門的なC++コースを取ってきました。私は彼らがこのプログラムを書くのを手伝ってくれましたが、私が理解できない奇妙なバグが1つあります。助けてくださったご提案は大変ありがとうございます。ありがとう!!C++ Int関数を変更しないでint値を返す

以下はコードです。問題は、add_loop関数の後で、int loop_sizeがランダムな値を取得することです。関数内では、それは持っていたはずの値を持ちますが、その後は変化します。

#include <iostream> 
#include <string> 
#include <stdlib.h> 
#include <time.h> 

using namespace std; 
#define STRING_SIZE 50 

void get_template (char StemLoop []) 
{ 
    char Template [STRING_SIZE]; 
    cout<<"Please enter a template for the stem:"; 
    cin>> Template; 
    strcpy (StemLoop, Template); 
} 

void add_loop (char StemLoop[], int loop_size) 
{ 

    char random_loop [STRING_SIZE]; 

    int random_array[STRING_SIZE]; 

    for (int i=0; i<loop_size; i++) 
    { 
     random_array[i] = rand() % 4; 
     if (random_array[i]==0) 
      random_loop[i]='A'; 
     else if (random_array[i]==1) 
      random_loop [i]='U'; 
     else if (random_array[i]==2) 
      random_loop [i]='G'; 
     else if (random_array[i]==3) 
      random_loop [i]='C'; 

    } 
    strcat (StemLoop, random_loop); 
} 

void add_complement(char StemLoop[], int loop_size) 
{ 

    int x =strlen(StemLoop); 
    int j=0; 
    char complement [STRING_SIZE]=""; 
    for (int i=0; i<(x-loop_size); i++) 
    { 
     if (StemLoop[i]=='A') 
      complement[j]='U'; 
     else if (StemLoop[i]=='U') 
      complement[j]='A'; 
     else if (StemLoop[i]=='G') 
      complement[j]='C'; 
     else if (StemLoop[i]=='C') 
      complement[j]='G'; 
     j++; 
    } 
    strcat(StemLoop,complement); 
} 

void main() 
{ 
    int loop_size=0; 
    cout<<"Please enter the size of the loop: "; 
    cin>>loop_size; 

    char StemLoop [STRING_SIZE]; 

    //Part1: the template 
    get_template (StemLoop); 

    //This is supposed to be the function that adds the loop of random "genes". 
    //It works, and within it the int loop_size is the correct value... 
    add_loop (StemLoop, loop_size); 
    /*...but here it is a random number. It's as if the random value generated 
    within the function is getting assigned to it. And of course, it's throwing off the 
    entire program. 
    */ 

    //Part#3: the complement 
    add_complement (StemLoop, loop_size); 
    cout<<"The complete stem-loop strand is:"<<StemLoop<<endl; 
} 
+0

入力するテンプレートのサイズはどれくらいですか?いくつかの制限やその他を適切にチェックしていないため、スタックオーバーフローが発生する可能性はほとんどありません。 –

+3

私は彼女を指導しています。私は "彼女の宿題をしなかった"。そして私はあなたにそれをするよう求めていません。小さなバグを見つけやすくするために。 – BIU

+0

(削除されたコメントに返信しました) – BIU

答えて

3

あなたはstrcatでそれを使用する前に、そのstrcatは、すべてのスタックの上に書くことができます0終端random_loopじゃありません。このお試しください:

random_loop[i] = 0; 
strcat (StemLoop, random_loop); 

をより深刻な問題は、あなたがstrcatに十分なスペースを持ってチェックしていないことが考えられます。

+0

ここでは、0終了がないことが問題です。デフォルトでは、配列は定義されていればゼロで埋められていないので、これを手動で行う必要があります(またはforループの最後の実行で文字列を終了させる)。 – SvenS

関連する問題