2017-08-23 5 views
-1

これはinputArrayという単語の配列からそれぞれのdelims値を取得し、whileの各ループの後に次の単語に移動するだけです。C++は文字の末尾から値を削除する

各単語はsubと呼ばれます。

「s」の末尾に単語が見つかると、「s」を削除して、sub =新しい単語にします。

私の現在のメソッドは、サブバックをstringTempという文字列に変換し、次に 's'を取り除き、それを文字subに戻します。

char inputDelim[] = " "; 
char* sub = strtok(InputArray, inputDelim); 
while(sub) 
{ 
    //This sets up the ability to find if 's' is at the end of the word 
    int n = strlen(sub); 
    int v = n; 
    char *vw = &sub[0u]; 
    v--; 

    ///////////////////// 
    //The problem is here 
    ///////////////////// 
    if(vw[v] == 's') 
    { 
     string stringTemp = string(sub); 
     stringTemp.erase(stringTemp.end() - 1); 
     sub = str.c_str();//This does not work. Can not convert const char* into char* 
     s = 1; 
     r = 1; 
    } 
    ...lots more code... 
    sub = strtok(NULL, inputDelim); 
} 

subは、異なる手段のコードでさらに使用されます。

誰でもこの方法の作業を手助けできますか、sub charの末尾に「s」を取り除く別の方法を教えてください。

私はこれに苦しんではいけませんが、悲しいことに私はです。

ありがとうございました!

+0

どのように機能しないのですか?あなたは 'sub'の値で何もしていません。 – interjay

+0

あなたはすぐに 'sub'を' sub = strtok(NULL、inputDelim); 'で上書きしますので、達成しようとしていることがわかりません –

+0

あなたの質問のタイトルは絶対に意味がありません! char_の_endのようなものはありません。 'char'値は分割不可能なものです。 ( 'strtok()'から離れてください)。 – user0042

答えて

0

ご指摘の正確別の問題があります:

//... 
int v = n; 
char *vw = &sub[0u]; 
v--; 

///////////////////// 
//The problem is here 
///////////////////// 
if(vw[v] == 's') // v points the the NULL char at the end of vw. 

// should read: 
if(vw[v - 1] == 's') // v points the the last char of string vw 

主な問題はある、あなたのInputArrayにはstrtokを使用して開始したら、あなたはそれを台無してはならないこと。 strtokはあなたの文字列の内容をほぼ所有しており、それを変更します。 subInputArrayを指しています)に書き込むと、strtokの内部ロジックが効果的に中断されます。

gettoからstd :: stringで作業することで、自分自身で苛立たしバグを救うことができました。 strtok()は完全ではありません...

このコードはC++ 03用です。 C++ 11では、std :: find_if_notとdeprecated std :: not1を導入しました。

#include <string> 
#include <iostream> 
#include <algorithm> 
#include <cctype> 

using namespace std; 

bool is_space(char c) 
{ 
    return isspace(static_cast<unsigned char>(c)) != 0; 
} 

int main() 
{ 
    string no_s; 
    //... 
    string phrase = "hello world and its riches"; 
    string::iterator p1; 
    string::iterator p2 = phrase.begin(); 
    while ((p1 = find_if(p2, phrase.end(), not1(ptr_fun(is_space)))) != phrase.end()) 
    { 
     p2 = find_if(p1 + 1, phrase.end(), is_space); 

     string sub(p1, p2); 
     if (*sub.rbegin() == 's') 
      sub.resize(sub.length() - 1); 

     no_s += sub + " "; 
    } 

    if (no_s.length()) 
     no_s.resize(no_s.length() - 1); 

    cout << no_s; 

    return 0; 
} 
+0

'vw [v]'は文字列の最後の文字です、 'vw [v + 1]'(つまり 'vrl [strlen(vw)]')はヌルターミネータです –

+0

ああ..私はv- - 。そのコードで同じことを意味する変数が多すぎます... –

関連する問題