0

stringaをchararray に変換してから、 a に戻し、 に変換stringしていvectorます。印刷しようとすると、次のようになります。

this
is
the
sentence iuִִ[nu@h?(h????X

などなど。これはコードです:

int main(int argc, char *argv[]){
    string s ="this is the sentence";
    char seq[sizeof(s)];
    strcpy(seq, "this is the sentence");
    vector<string> vec = split(seq);
    printWords(vec);

    return 0;
}

これが func.cpp ファイルです。1 つの関数は char を文字列ベクトルに分割し、もう 1 つは印刷です。

vector<string> split(char sentence[]){
    vector<string> vecto;
    int i=0;
    int size= strlen(sentence);
    while((unsigned)i< size){
        string s;
        char c =' ';
        while(sentence[i]!=c){
            s=s+sentence[i];
            i+=1;
        }
        vecto.push_back(s);

        i+=1;
    }

    return vecto;
}

void printWords(vector<string> words){
    int i=0;
    while ((unsigned)i<words.size()){
        string s = words.at(i);
        cout << words.at(i) << endl;
        i+=1;
    }
}
4

2 に答える 2

1

上記の答えを理解したら、次のような (C++11) など、エラーが発生しにくいスタイルを試してください。

#include <iostream>
#include <sstream>
#include <vector>

using namespace std;
int main(){
  string s{"this is the sentence"};
  stringstream sStream;
  sStream<<s;
  string word;
  vector<string> vec;
  while(sStream >> word){
    vec.emplace_back(word);
  }
  for(auto &w : vec){
    cout << "a word: " << w <<endl;
  }
}
于 2012-11-02T19:39:43.997 に答える
1

あなたの問題の1つはそれsizeof(s) != s.size()です。

これを試して:

char letters = new char[s.size() + 1]; // +1 for the null terminator.

この式は、文字列内の文字数ではなく、オブジェクトsizeof(s)のサイズを返します。std::stringオブジェクトはstd::string、文字列の内容を超えている可能性があります。

また、std::string::operator[]文字列内の個々の文字にアクセスするために使用してみてください。

例:

string s = "this is it";
char c = s[5]; // returns 'i' from "is".

std::stringなどの の検索機能の使用も検討する必要がありますstd::string::find_first_of

例:

unsigned int position = s.find_first_of(' ');

もう 1 つの便利な関数はsubstrメソッドです。

   std::string word = s.substr(0, position);
于 2012-11-02T19:31:21.183 に答える