C :打印有线字符串

c++ : printing wired string

本文关键字:字符串 打印      更新时间:2023-10-16

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

您的问题之一是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位置= s.find_first_of('');

另一个有用的功能是substr方法:

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