C :打印有线字符串
c++ : printing wired string
我将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);
相关文章:
- 有没有办法将字符串打印为文字?
- 如何通过标准字符串打印 ostream 变量的值?
- 这个随机字符串打印代码有什么问题?
- 比较 C++ 字符串打印中的两个整数数组
- 在C++中从后缀表达式字符串打印单个操作
- 没有得到 ASCII 编号 = 7 的字符串打印输出
- C++字符串到字符串打印不正确,无法获取 unicode 路径
- 如何从数组 c++ 中的字符串打印第 N 个字符
- 将 LPCWSTR 字符串打印到文件
- C++正在将DWORD_PTR*字符串打印到文件中
- 使用#define字符串打印f和警告
- 使用格式字符串打印类
- 如何将字符转换为字符串,并从字符串打印到main函数
- 将vector中结构体的成员字符串打印到cout流
- fprintf() / std::cout 不会将部分字符串打印到 stdout/stderr
- 为什么ostream为定义为' volatile char[] '的字符串打印' 1 ' ?
- c++文件读取和字符串打印
- 如何使用一个字符串打印此unicode行
- 按字符串打印日期
- 如何用c++将字符串打印到控制台