[英]Can't seem to print my string out
So this is a fragment of my code:所以这是我的代码片段:
void reverse(string query, string reverseQuery) {
unsigned int i;
for(i=0; i<query.length(); i++) {
reverseQuery[i] = query[query.length()-1-i];
}
cout << reverseQuery << endl;
return;
}
The headers for iostream, string and using namespace std were also included in the code. iostream、string 和 using namespace std 的标头也包含在代码中。 The problem I am facing is that when I try to output the string reverseQuery nothing comes out.
我面临的问题是,当我尝试输出字符串 reverseQuery 时,什么也没有出现。 Anyone knows why?
有谁知道为什么? Thanks!
谢谢!
Your fragment should look like:您的片段应如下所示:
std::string reverse(const string& query) {
std::string reverseQuery(query.length(),0); // <<<<< Ensure that the size is the same
for(unsigned i=0; i<query.length(); i++) {
reverseQuery[i] = query[query.length()-1-i];
}
// cout << reverseQuery << endl;
return reverseQuery;
}
The way shorter and idiomatic code to achieve that with a standard c++ string is使用标准 C++ 字符串实现该目标的更短且惯用的代码的方式是
std::string reverseQuery(query);
std::reverse(std::begin(reverseQuery),std::end(reverseQuery));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.