C++ Int 在不应该更改它的函数后获取随机值
C++ Int getting random value after function that isn't supposed to change it
好的,是的,这是家庭作业,但不是我的。我有一个朋友正在学习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;
}
在strcat
中使用random_loop
之前,并不是0终止它,因此strcat
可以在整个堆栈中进行写入。试试这个:
random_loop[i] = 0;
strcat (StemLoop, random_loop);
一个更严重的问题可能是您没有检查是否有足够的空间容纳strcat
。
相关文章:
- constexpr 函数获取常量字符*
- 在 C++ 中将函数获取和设置为虚拟函数
- 函数获取参数的变量列表并将它们转换为一系列字节?
- 如何在C++中从Lua函数获取返回表?
- C++使用第二个函数获取字符数组的长度
- 在编译时通过 constexpr 或模板函数获取多维 std::array 的大小
- 包装 C API 通过C++接受迭代器的函数获取原始指针
- 如何指定创建文件函数获取未缓存的结果?
- 从函数获取 char* 后的条件 gdb 断点
- 如何在不使用返回的情况下从函数获取变量的地址(指针)
- RCPP:将布尔值传递在列表中从R到C 函数的错误,该函数获取RCPP ::列表
- 从 Rcpp c++ 函数获取 r 函数参数
- 如何从子例程函数获取到 main 函数的返回值
- 使用 getline 函数获取分段错误
- 如何使用getForegroundWindow函数获取模块
- C++,无法使用 .size() 函数获取有效的矢量大小
- 如何从调用的函数获取返回值,该函数在 TBB 中的另一个线程中执行
- 如何使用C或C++函数获取特定文件夹中的文件数
- 如何在 c++ 中从函数获取返回值而不为其变量赋值
- 如何使用strlen函数获取字符串的长度