在C ++中遇到“字符串下标超出范围”的问题

问题描述 投票:0回答:1

每当我尝试输入't'时,它返回一个“字符串下标超出范围”

while ((y != sequence.length()) && (base != 'u' || base != 't')) {
        base = sequence[y];
        y++;
        if (base == 't')
        {
            //if the sequence is DNA
            while (sequence[y] != sequence[z])
            {
                if (sequence[y] == 't')
                {
                    mRNA_sequence += 'a';
                }
                else if (sequence[y] == 'a')
                {
                    mRNA_sequence += 'u';
                }
                else if (sequence[y] == 'c')
                {
                    mRNA_sequence += 'g';
                }
                else if (sequence[y] == 'g')
                {
                    mRNA_sequence += 'c';
                }
                y++;
            }
            DNA = sequence;
            sequence = mRNA_sequence;
        }
    }

如果我输入't',它应该把它变成'a'。它适用于其余部分。

c++ visual-studio
1个回答
0
投票

@Yksisarvinen是对的。 y的增加是你的首要问题。它适用于u而不适用于t的另一个原因是因为您的代码不对任何其他字母进行处理。 if (base == 't')是您的代码段中唯一提供的案例。

您还使用y作为外部 - while循环和内部 - 循环的变量。这可能是预期的行为,只是要谨慎。你的内部循环将增加y,而新的更大的值将是外部while循环中使用的y值。

你可以在while循环中设置DNA = sequence;sequence = mRNA_sequence;而不会破坏它。请记住,while循环现在将有一个新的'序列'用于while循环的sequence.length()调用。因为我相信你的代码对于DNA和mRNA序列具有相同的长度值,你可能会偷偷摸摸,但这很危险。你的病情在(y != sequence.length())状态下,如果mRNA_sequence比初始序列短,那么y可能大于长度,这仍然会通过你的状态。

© www.soinside.com 2019 - 2024. All rights reserved.