【问题标题】:My program is deleting a character from a string, how to avoid that?我的程序正在从字符串中删除一个字符,如何避免这种情况?
【发布时间】:2014-08-25 01:31:29
【问题描述】:

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

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

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

  1. aabcabcd
  2. dabcd <<-- Incorrect

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

a b c d 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,但这段代码有什么问题?谢谢!

【问题讨论】:

  • 您可以将char* gen = new char[3]; 替换为char * gen[3];,因为数组大小是恒定的。
  • 这 -> dna[index]=gen[0] 是一个静默错误。
  • “这段代码有什么问题?” - 基本上,它最大的问题是你编写了一个带有一些 C++ 修饰的 C 程序。不要使用fscanf 和朋友,不要使用原始数组。使用#include &lt;iostream&gt; 并使用其中的内容,然后使用std::string 和/或std::vector
  • @WhozCraig 没有编译警告!

标签: c++ string


【解决方案1】:

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

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

【讨论】:

  • +1 它比赋值操作更糟糕。由于对表达式的其余部分分配了一个意外的布尔 eval,问题变得更加复杂。
  • 我不敢相信我错过了。它现在正在工作。我将解决另一个问题,即替换字符串。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 2019-11-20
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多