s7mahess
Goto Top

Cpp Syntax Problem bei String copy replace

Hallo meine Aufgabe ist es dies hier zu bewältigen:

I have a special piece of text that represents a specific value. Here's how I calculate it:
  1. Start reading left to right
  2. If a character is a digit, I add it to my sum
  3. If it's an 'x', I remove it and go left two places
  4. Continue until I hit the end of the string
For example, the string '123x456' has a value of 26.

What is the value of '93752xxx746x27x1754xx90x93xxxxx238x44x75xx08750912738x8461x8759383xx328x4x4935903x6x5550360535004x0xx945958961296x267x8842xxx5x6xx61x4x48482x80xxx83316843x7x4x83x9521731xxx25x51xx457x6x5x9698222x771237745034x5133592x27xx8x87xx35221x36x0x50x23x7x63x998418xx'?

#include <iostream>
#include <string>

using namespace std;

int main(){
  int i_length_base,i_length_copy,i_i,i_sum;
  char c_c='x',c_replace[1];  
  size_t found;
  string base="93752xxx";  
  //746x27x1754xx90x93xxxxx238x44x75xx08750912738x8461x8759383xx328x4x4935903x6x5550360535004x0xx945958961296x267x8842xxx5x6xx61x4x48482x80xxx83316843x7x4x83x9521731xxx25x51xx457x6x5x9698222x771237745034x5133592x27xx8x87xx35221x36x0x50x23x7x63x998418xx"; 

  cout << "string is: "<< base << endl;  



  while ((found=base.find(c_c))!=-1){
    cout << "first '" << c_c << "' found at: " << int(found) << endl;  
    i_length_base=base.length();
    cout << "actual strlength is: "<< i_length_base << endl;  

    i_length_copy=base.copy(c_replace,2,found-2);
    cout << "c_c: " << c_c << endl;     // warum ändert er mir in der Zeile vorher c_c in 2 um !!!!!!!  

    c_replace[i_length_copy]='\0';  
    cout << "actual c_replace is: "<< c_replace << c_replace[1] << endl;  

    base.replace(found,1,c_replace);
    cout << "new string is: " << base << "\n\n";  

    c_c='x';                           // wenn ich die stelle hier auskommentiere stürzt alles ab  
  }

  for (i_i=0; i_i < base.length(); i_i++){
    i_sum=i_sum+(base.at(i_i)-48);
  }
  cout << "Result i_sum: " << i_sum;  

  return(0);
}

Die Berechnung des neuen kommt später noch, mein Problem ist in den Comments beschrieben, ich kann das Problem zwar mit dem c_c='x'; umgehen, aber das klärt meine Frage warum in der Zeile i_length_copy=base.copy(c_replace,2,found-2); c_c in 2 umgeändert wird nicht.

Bitte um Erklärung.


MfG & Danke

Martin

Content-Key: 145499

Url: https://administrator.de/contentid/145499

Printed on: April 26, 2024 at 08:04 o'clock