我写的代码应该计算char指针列表中的a,c,t和g的数量。然后,如果输入的char不是a,c,t或g,则应该将无效字母添加到char列表invalidBase中。相反,当我输入数据agtcpoop时,它打印出Invalid Base:但是当它应该打印出poop时,chars不在那里。请帮忙!这是代码:
{{1}}
答案 0 :(得分:3)
Yoy通过使用具有自动存储持续时间的未初始化变量的值来调用未定义行为,这是不确定的。
改进:
j
时增加计数器invalidBase
。j
确定要打印的长度。改进代码:
void countBase(char *p)
{
int aCount = 0, cCount = 0, tCount = 0, gCount = 0;
char invalidBase[100];
int i, j=0;
while(*p != '\0')
{
if(*p == 'A' || *p == 'a')
{
aCount++;
}
else if(*p == 'C' || *p == 'c')
{
cCount++;
}
else if(*p == 'T' || *p == 't')
{
tCount++;
}
else if(*p == 'G' || *p == 'g')
{
gCount++;
}
else
{
if(j < (int)(sizeof(invalidBase) / sizeof(*invalidBase))) /* avoid buffer overrun */
{
invalidBase[j] = *p;
j++;
}
}
p++;
}
for(i = 0; i < j; i++)
{
printf("Invalid Base: %c\n", invalidBase[i]);
}
printf(" A: %i\n C: %i\n T: %i\n G: %i\n", aCount, cCount, tCount, gCount);
}
请注意,您可以使用switch
语句代替这些if-else
语句。
void countBase(char *p)
{
int aCount = 0, cCount = 0, tCount = 0, gCount = 0;
char invalidBase[100];
int i, j=0;
while(*p != '\0')
{
switch(*p)
{
case 'A':
case 'a':
aCount++;
break;
case 'C':
case 'c':
cCount++;
break;
case 'T':
case 't':
tCount++;
break;
case 'G':
case 'g':
gCount++;
break;
default:
if(j < (int)(sizeof(invalidBase) / sizeof(*invalidBase))) /* avoid buffer overrun */
{
invalidBase[j] = *p;
j++;
}
break;
}
p++;
}
for(i = 0; i < j; i++)
{
printf("Invalid Base: %c\n", invalidBase[i]);
}
printf(" A: %i\n C: %i\n T: %i\n G: %i\n", aCount, cCount, tCount, gCount);
}
答案 1 :(得分:0)
#include<stdio.h>
#include<stdlib.h>
void countBase(char *p) {
int aCount = 0, cCount = 0, tCount = 0, gCount = 0;
char invalidBase[100];
int i, j=0;
while(*p != '\0') {
if(tolower(*p) == 'a') {
aCount++;
}
else if(tolower(*p) == 'c') {
cCount++;
}
else if(tolower(*p) == 't') {
tCount++;
}
else if(tolower(*p) == 'g') {
gCount++;
}
else {
// This is the correct place to increment j.
invalidBase[j++] = *p;
}
// The following line is wrong. You can only increment j if an invalid
// base was found and inserted on the array.
// j++;
p++;
}
// Your code lacked the "end of string" delimitation.
invalidBase[j] = '\0';
for(i = 0; invalidBase[i] != '\0'; i++) {
printf("Invalid Base: %c\n", invalidBase[i]);
}
printf(" A: %i\n C: %i\n T: %i\n G: %i\n", aCount, cCount, tCount, gCount);
}
int main(){
printf("Testing '%s'\n", "agtcpoop");
countBase("agtcpoop");
puts("***********************************");
printf("Testing '%s'\n", "a");
countBase("a");
puts("***********************************");
printf("Testing '%s'\n", "");
countBase("");
puts("***********************************");
printf("Testing '%s'\n", "p");
countBase("p");
return 0;
}