gpt4 book ai didi

c - C 将字符输入数组时出现段错误

转载 作者:行者123 更新时间:2023-11-30 19:15:37 25 4
gpt4 key购买 nike

我试图将各种核苷酸碱基输入到阵列中,但我的阵列出现问题。它要么在我输入一个字符后返回段错误,要么在提示我输入另一个字符之前循环运行 3 次。感谢您提前提供的帮助。

这是我的代码:

#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;
}

最佳答案

你的错误是scanf("%c",核苷酸);scanf("%c",&核苷酸);更改它,因为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;
}

关于c - C 将字符输入数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com