gpt4 book ai didi

c++ - 我的程序正在从字符串中删除一个字符,如何避免这种情况?

转载 作者:行者123 更新时间:2023-11-30 04:01:56 25 4
gpt4 key购买 nike

我有一个程序,它应该找到一个包含 3 个字符的字符串,将“abc”变成一个更长的字符串,比如“aabccbd”,然后用另一个字符(比如“d”)替换原始字符串中的巧合。所以。给定这些字符串,结果将是:

  1. aabcabcd
  2. adabcd <<-- another iteration
  3. addd <<-- Final result

而且我已经编写了一些代码行,我相信可以解决替换给定序列的问题(仍然没有编写字符替换的程序)。但问题是,当我用给定的字符替换序列时,序列之前的字符被删除。示例:

  1. aabcabcd
  2. dabcd <<-- Incorrect

可能有什么问题?请检查我的代码。从具有以下格式的 .txt 文件中读取序列:

a b c d <- 序列和交换字符。 (序列总是 3 个字符长) abcdefakxoqp333 <- 我应该在其中搜索序列的完整字符串。

Code:
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
char* gen = new char[3];
char simp;
char dna[10001];

int main() {
int len;
//Reading file and assigning values.
FILE *input = fopen("input.txt","rt");
fscanf(input,"%c %c %c %c",&gen[0],&gen[1],&gen[2],&simp);
fscanf(input,"%s",&dna);
fclose(input);
len = strlen(dna);
//In this part dna has the 2nd line of input.txt
for(int i=0;i<len;i++){
cout << dna[i];
}
cout << endl;
//Searching for coincidences.

int dnaLen = len; //dna Lenght, this one will change over time.
bool found=false;
int index=0; //Index will be reseted as well when we make a change!!
while(index<dnaLen-2) {
cout << "Entering WHILE with index=" << index << "\n";
cout << "Examining: " << dna[index] << dna[index+1] << dna[index+2] << endl;
if(dna[index]=gen[0] && dna[index+1]==gen[1] && dna[index+2]==gen[2]){
//Replace dna[index] for simp AND displace the dna array
dna[index]=simp;
for(int i=0;i<dnaLen;i++){
cout << dna[i];
}
cout << endl;
index =0;
dnaLen=dnaLen-2;
}
index++;
}
return 0;
}

我知道我可以尝试使用正则表达式,问题是我在使用 C++11 方面有点受限。我也知道我可以使用 string::replace但是这段代码有什么问题?谢谢!

最佳答案

这不是比较而是赋值,把=换成==

if(dna[index]=gen[0]...

关于c++ - 我的程序正在从字符串中删除一个字符,如何避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25474303/

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