C++ c++;:打印有线字符串

C++ c++;:打印有线字符串,c++,string,vector,C++,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&l

我正在将
字符串
转换为
字符
数组,然后再转换回
字符串
并转换为
向量
。 当我尝试打印时,我得到以下信息:

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;
}
intmain(intargc,char*argv[]){
string s=“这是句子”;
字符顺序[大小];
strcpy(以下简称“本句”);
向量向量=拆分(seq);
印刷字;
返回0;
}
这是func.cpp文件。一个函数将字符拆分为字符串向量,另一个函数用于打印:

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;
    }
}
向量拆分(字符句子[]){
向量向量机;
int i=0;
int size=strlen(句子);
而((无符号)i而((未签名)i您的问题之一是
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 < /C> >的搜索功能,如<代码> STD::String: 示例:

string s = "this is it";
char c = s[5]; // returns 'i' from "is".
无符号整数位置=s.find_first_of(“”)

另一个有用的函数是
substr
方法:

   std::string word = s.substr(0, position);

理解上述答案后,尝试一种不太容易出错的风格,类似于(C++11):

#包括
#包括
#包括
使用名称空间std;
int main(){
字符串s{“这是句子”};
溪流;
(流字){
向量后置(word);
}
用于(自动&w:vec){

不能使用
s.length()
s.size()
,而不能使用
sizeof(s)
sizeof(s)
std::string
的大小(以字节为单位)。也是空值的原因。更改了它…仍然会出现相同的错误。对于char数组,我应该使用什么?strln?是的,对于C字符串,使用
strlen
。无论如何,传递到
split
中的字符串也会越界。它会寻找一个空格,直到找到为止,甚至超过了在退出之前,字符串的结尾。这也可以通过检查null来修复。顺便问一下,为什么称它为wired?仍然得到相同的结果。可能是strln()?它工作了!问题在这一行:while(句子[i]!=c){它超出了界限。thanx u all!