I apologize in advance, as I asked the same question in a previous post, but, as someone correctly pointed out, I did not publish the real code. So I ask the same question again, trying to be clearer than before.
I am creating as an exercise a program that controls the string. In particular, I want to remove the part of the line enclosed between 2 '*'. I must emphasize that I have successfully created the same program with the library string function; in fact, the problem is related to the manipulation of this string with char pointers. I will lay out the full code and discuss it in detail.
#include <iostream>
#include <string>
using namespace std;
int main() {
string frase;
getline (cin, frase);
int size = frase.size();
cout << frase[0];
char* pa1 = NULL;
char* pa2 = NULL;
bool stop = false;
for(int i = 0; i < size - 1 || stop == true; i++){
if(frase[i] == '*'){
if(*pa1 == '*'){
pa2 = &frase[i];
stop = true;
}
pa1 = &frase[i];
}
}
if(pa2 == NULL){
if(pa1 == NULL){
cout << "Non ci sono asterischi. Non verrà eliminata nessuna parola.\n\n";
}
cout << "C'è un solo asterisco. Verrà eliminato unicamente l'asterisco.\n\n";
for(; pa1 < &frase[size - 1]; pa1++){
*pa1 = *(pa1 + 1);
}
}
else{
for(; pa1 < pa2 + 1; pa1++){
*pa1 = *(pa1 + 1);
}
}
cout << "La frase dopo l'eliminazione è:\n" << frase;
return 0;
}
Before publishing, I made some efforts to understand the essence of the problem. I saw an unexpected behavior: if I initialize pointers to a memory address, for example:
pa1 = &frase[i];
, ( "if" for n.1) , ( ), :
cout << *pa1;
. , pa2 2- , . pa1 "NULL" .
2 :
1 - , char, . , , .
2 - , , "" . , for n.2 n.3 ( ).
, char [], , , , char. ; ( , , , - , ). , . .
EDIT: , , , , , int , , . , , .
EDIT 2: @lilscent , . pa1 pa2
pa1 = &frase[0];
pa2 = nullptr;
3: , , break . for, , , . , :
if(pa2 == nullptr){
if(pa1 == &frase[0]){
cout << "Non ci sono asterischi. Non verrà eliminata nessuna parola.\n\n";
}
else{
cout << "C'è un solo asterisco. Verrà eliminato unicamente l'asterisco.\n\n";
for(; pa1 < &frase[size - 1]; pa1++){
*pa1 = *(pa1 + 1);
}
*pa1 = ' ';
}
}
EDIT 4: . :
else{
*pa2 = ' ';
pa2+= 2;
for(; pa1 < pa2 + 1 && pa2 < &frase[size]; pa1++, pa2++){
*pa1 = *pa2;
*pa2 = ' ';
}
*pa2 = ' ';
}
! , .
: NikosC. . , . !