string长度计算问题
如题,下面是代码,为什么打印出来tmp.length()不是我想要的长度?
#include <stdio.h>#include <stdlib.h>#include <iostream>#include <fstream>#include <string>using namespace std;intmain(){ string str = ""; string tmp = ""; ifstream in("test.txt"); while(getline(in, str)) { cout<<str.length()<<" "<<str<<endl; for(int i = 0; i < str.length(); i++) { cout<<std::hex<<(int)str[i]<<" "; tmp.append(&str[i]); } cout<<endl<<tmp.length()<<"----"<<tmp<<"----"<<endl; tmp = ""; } in.close(); return 0;}
#include <stdio.h>#include <stdlib.h>#include <iostream>#include <fstream>#include <string>using namespace std;intmain(){ string str = ""; string tmp = ""; ifstream in("F:\\11.txt"); char buf[2] = {0}; while(getline(in, str)) { cout<<str.length()<<" "<<str<<endl; for(int i = 0; i < str.length(); i++) { cout<<std::hex<<(int)str[i]<<" "; buf[0] = str[i]; tmp.append(buf); } cout<<endl<<tmp.length()<<"----"<<tmp<<"----"<<endl; tmp = ""; } in.close(); return 0;}
[解决办法]
#include <stdio.h>#include <stdlib.h>#include <iostream>#include <fstream>#include <string>using namespace std;int main(){ string str = ""; string tmp = ""; ifstream in("test.txt"); while(getline(in, str)) { cout<<str.length()<<" "<<str<<endl; for(int i = 0; i < str.length(); i++) { cout<<std::hex<<(int)str[i]<<" "; tmp.append(&str[i], 1); // 添加一个字符(默认是添加字符串的) } cout<<std::dec; // 返回到十进制输出 //cout<<endl<<endl; cout<<endl<<tmp.length()<<"----"<<tmp<<"----"<<endl<<endl; tmp = ""; } in.close(); return 0;}
[解决办法]
basic_string::append
basic_string& append(const E *s);
basic_string& append(const E *s, size_type n);
basic_string& append(const basic_string& str,
size_type pos, size_type n);
basic_string& append(const basic_string& str);
basic_string& append(size_type n, E c);
basic_string& append(const_iterator first, const_iterator last);
The member template function appends the operand sequence to the end of the sequence controlled by *this, then returns *this.
In this implementation, if a translator does not support member template functions, the template:
template<class InIt>
basic_string& append(InIt first, InIt last);
is replaced by:
basic_string& append(const_iterator first, const_iterator last);
See the related sample program.