gpt4 book ai didi

C++ : printing wired string

转载 作者:行者123 更新时间:2023-11-28 03:28:47 26 4
gpt4 key购买 nike

我正在将 string 转换为 char 数组,然后再转换回 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 文件。一个函数将 char 拆分为字符串 vector ,另一个是打印:

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;
}
}

最佳答案

理解上面的答案后,尝试一种不太容易出错的风格,更像这样(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;
}
}

关于C++ : printing wired string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com