2016-10-04 10 views
-2

組み込み関数を使用せずに文字列gを削除し、ポインタと括弧を使用できる変数を1つだけ使用して文字列gを削除すると仮定します。私はコードを持っていますが、新しい編集された文字列ではなく空の文字列を返し続けます。c文字列のコピーが空の文字列に失敗する

#include <iostream> 

using namespace std; 


void deleteG(char *str) { 
    char *temp = str; //make new pointer,pointing at existing, now i have initialized and enough size. 

    while (*str != '\0') { //while the c-string does not reach null termination 

     if (*str != 'g' || *str != 'G') { // if the value of the current position is not the character g or G proceed. 
      *temp = *str;//copy value over 
      temp++;//increase count 
     } 
     str++;//increase count to next char and check again above is if does not equal g or G 
    } 
//this should now copy the new string over to the old string overriding all characters 
    while (*temp != '\0') { 
     *str = *temp; 
     str++; 
     temp++; 

    } 

} 

int main() { 
    char msg[100] = "I recall the glass gate next to Gus in Lagos, near the gold bridge."; 
    deleteG(msg); 
    cout << msg; // prints I recall the lass ate next to us in Laos, near the old bride. 
} 
+6

すべてが「g」でなく「G」でもありません。 –

+0

はい、out gまたはGを使用して文字列をコピーしてください –

+2

||の代わりに&&を使用する必要があります。そうでない場合は何も渡されません。 – ZenJ

答えて

0

に変更して:文字にかかわらず、ケースのないグラムであること

if (*str != 'g' && *str != 'G') { 

この条件をチェックします。

+0

@BaummitAugen私はしましたか?ところで、投稿に「組み込み関数を使用せずに」と言っても私はコメントを削除しました。 –

+1

@ KenY-Nですので、https://stackoverflow.com/questions/21805674/do-i-need-to-cast-to-unsigned-char-before-calling-toupper私が言ったように、C + +は時々ひどいです。 (参考のために、Kenは '&&'と比較する代わりに 'std :: toupper(* str)!= 'G''を比較することを提案しました)。 –

+0

もnullを移動するコードを編集する必要がありました古い文字列の終わりに達したら文字を前方に送り、新しい文字列を短くして他には何も印刷しません。 –

3
if (*str != 'g' || *str != 'G') { 

この条件は常にtrueであるため、常に文字がコピーされます。

どうしてそれはいつも真実ですか?

考えてみましょう - 文字はgまたはGなどです。

gの場合、*str != 'g'は偽、*str != 'G'は真、false || trueは真であるため、条件は真です。

Gの場合は*str != 'g'が真、*str != 'G'が偽、true || falseが真であるため、条件は真です。

それ以外の場合は、*str != 'g'が真で、*str != 'G'が真で、true || trueが真であるため、条件は真です。

関連する問題