读书人

string长度计算有关问题

发布时间: 2012-04-03 12:38:19 作者: rapoo

string长度计算问题
如题,下面是代码,为什么打印出来tmp.length()不是我想要的长度?

C/C++ code
#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;}


[解决办法]
1. 是不是应该去掉取地址符? tmp.append(str[i]);
2. in.close()不需要显示调用,析够会关闭文件。
[解决办法]
不是str.size()吗?
[解决办法]
你的tmp.append(&str[i]);这里不对
C/C++ code
#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;}
[解决办法]
C/C++ code
#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.

读书人网 >C++

热点推荐