【问题标题】:C++ Int getting random value after function that isn't supposed to change itC++ Int 在不应该改变它的函数之后获得随机值
【发布时间】:2012-02-12 00:39:47
【问题描述】:

好的 - 是的,这是作业,但不是我的。我有一个朋友正在上 C++ 入门课程,他向我寻求帮助,我帮助他们编写了这个程序,但是有一个奇怪的错误我无法弄清楚。任何有用的建议将不胜感激。谢谢!!

以下是代码。问题是在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;
}

【问题讨论】:

  • 您输入的模板大小。您几乎可以肯定某处发生了堆栈溢出,因为您没有正确检查某些限制或其他限制。
  • 我正在辅导她。我没有“为她做功课”。我也不要求你这样做。只是为了帮助我找到一个小错误。
  • (这是对已被删除的评论的回复)

标签: c++ random int


【解决方案1】:

strcat 中使用它之前,你不是 0 终止 random_loop,所以 strcat 可以写在你的堆栈上。试试这个:

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

一个更严重的问题可能是你没有检查你有足够的空间来strcat

【讨论】:

  • 我认为缺少 0 终止是这里的问题。请记住,默认情况下,数组在定义时不会填充零,您必须手动执行此操作(或让 for 循环的最后执行终止字符串)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-27
相关资源
最近更新 更多