我试图将各种核苷酸碱基输入到阵列中,但我的阵列存在问题。我输入一个字符后返回分段错误,或者在提示我输入另一个字符之前循环运行3x。感谢您的帮助。
这是我的代码:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main(void)
{
char strand[20];
char nucleotide;
int position=0;
while(position<20)
{
printf("Enter one capital character:\n");
scanf("%c",nucleotide);
if(toupper(nucleotide) == 'A')
{
printf("You entered an A\n",nucleotide);
strand[position] = nucleotide; // store the letter in an array
position = position + 1; // gives the new letter a position in the array
}
else if(toupper(nucleotide) == 'G')
{
printf("You entered a G\n");
strand[position] = nucleotide; // store the letter in an array
position = position + 1; // gives the new letter a position in the array
}
else if(toupper(nucleotide) == 'C')
{
printf("You entered a C\n");
strand[position] = nucleotide; // store the letter in an array
position = position + 1; // gives the new letter a position in the array
}
else if(toupper(nucleotide) == 'U')
{
printf("You entered a U\n");
strand[position] = nucleotide; // store the letter in an array
position = position + 1; // gives the new letter a position in the array
}
else
{
printf("You have not entered a valid character.\n Please enter a character found in an RNA strand.\n");
}
printf("Congratulations, you entered %c\n",nucleotide);
}
return 0;
}
答案 0 :(得分:1)
你的错误是scanf("%c",nucleotide);
用scanf("%c",&nucleotide);
更改它,因为scanf接受指针作为参数。
此外,您不需要知道输入了哪个字符,您可以这样做:
#include<stdio.h>
#include<ctype.h>
int main(void) {
char strand[20];
char nucleotide;
int position = 0, i;
while (position < 20) {
printf("Enter one capital character:\n");
scanf("%c", &nucleotide);
if (toupper(nucleotide) == 'A' || toupper(nucleotide) == 'G' || toupper(nucleotide) == 'C' ||
toupper(nucleotide) == 'U') {
printf("You entered an %c\n", toupper(nucleotide));
strand[position] = nucleotide; // store the letter in an array
++position;// gives the new letter a position in the array
} else
printf("You have not entered a valid character.\n Please enter a character found in an RNA strand.\n");
printf("Congratulations, you entered %c\n", nucleotide);
}
printf("Your sequence is: ");
for (i = 0; i < 20; ++i)
printf("%c", strand[i]);
printf("\n");
return 0;
}
答案 1 :(得分:0)
你已经将&amp; -Symbol留在了...... {scanf(&#34;%c&#34;,核苷酸); }
while(position<20)
{
printf("Enter one capital character:\n");
scanf("%c",nucleotide);
if(toupper(nucleotide) == 'A')
很多时候,当它显示分段错误时,首先检查&#39;&amp;&#39;在scanf() 还有其他原因,你可以从任何好的c网站上读到这个...或者是C语言的书籍......分段错误总是运行时错误...它永远不会在编译时显示错误....
答案 2 :(得分:0)
当我编译你的代码时,我从编译器中得到了这个。
gcc main.c
main.c:在函数'main'中:
main.c:20:9:警告:格式'%c'需要类型'char *'的参数,但参数2的类型为'int'[-Wformat]
编译器告诉你它正在期望参数2的类型为char *。你的第二个参数是nucleotide
,你声明它是char类型。
在这种特殊情况下,解决方案是在&
的左侧添加nucleotide
,因为它返回一个指向核苷酸的指针,这是scanf期待的第二个参数。
但重要的一点是,你应该阅读编译器警告和错误,因为它们通常足以知道问题所在。