注册 登录
编程论坛 C++教室

请教string的赋值问题

kspliusa 发布于 2010-04-11 22:24, 889 次点击
// 编译环境  DEV C++
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string str_text_one;
    char source[] = "Hello";
   
    int i=0;
    while (source[i]) {
        str_text_one[i] = source[i]; // 这样赋值为啥不行呢
        i++;               
    }
    cout << "the length :" << str_text_one.length () << endl;
    cout << "str_text_one :" << str_text_one << endl;
     
    cout << "str_text_one :";
    for (i=0; i<strlen(source); i++) // 这样输出str_text_one中有值
        cout << str_text_one[i];
    cout << endl;
   
    str_text_one = source; // 这样赋值可以 上面为啥不行呢?
    int str_text_one_len = str_text_one.size ();
   
    cout << "str_text_one_len = " << str_text_one_len <<endl;
    cout << "str_text_one is :" << str_text_one << endl;
   
    system ("PAUSE");
    return 0;
}
问题如注释。。。
6 回复
#2
yyblackyy2010-04-11 23:52
string str_text_one;
 str_text_one[i] = source[i]; //str_test_one 中没有元素 怎么赋值啊 所以系统崩溃了
改成 string str_test_one(6,' '); //这样就行了,楼主试试吧~
#3
kspliusa2010-04-12 12:45
回复 2楼 yyblackyy
可以讲讲为什么吗?结果不是目的,目的是搞清楚原理啊。。。请指教。。。。
#4
yyblackyy2010-04-12 14:51
晕,不是说了吗,str_test_one 中没有元素 怎么赋值啊 所以系统崩溃了
就像 定义了 int a[1];而楼主却在 使用 a[1],数组的下标出界了,错误!而这里的str_test_one 没有元素,楼主怎么能使用str_test_one [1]呢,
所以错了,后果就是程序beng了
#5
asdjc2010-04-13 16:27
加点解释,主要是空间的问题,str_test_one 的空间不够。
#6
flyingzc2010-04-13 17:30
char source[] = "Hello";
这里[]不填,默认值为多少啊
#7
kspliusa2010-04-13 22:21
回复 4楼 yyblackyy
可是向后面这样输出为什么还有值啊?for (i=0; i<strlen(source); i++) // 这样输出str_text_one中有值
                                       cout << str_text_one[i];
??
1