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

运行结果不同于预期

apanyue 发布于 2013-08-20 15:57, 405 次点击
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{vector<const char*> cvec;
    string s1;
    while(cin>>s1&&s1!="end")
        cvec.push_back(s1.c_str());
    for(vector<const char*>::iterator it=cvec.begin();it!=cvec.end();++it)
        cout<<*it<<endl;
   
    return 0;

}

运行结果为:
ab cd end
end
end
Press any key to continue!
3 回复
#2
rjsp2013-08-20 16:36
你存储的都是 s1 的地址值

程序代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    vector<string> cvec;
    for( string s; cin>>s && s!="end"; )
        cvec.push_back( s );

    for( vector<string>::const_iterator itor=cvec.begin(); itor!=cvec.end(); ++itor )
        cout << *itor << endl;

    return 0;
}

#3
apanyue2013-08-21 09:48
回复 2楼 rjsp
vector<string> 容器里到底存储的是什么? 是string里第一个字符的地址,还是整个push_back进去的字符串的副本?
系统处理字符串,就是把字符串当成字符指针处理吗?
我的代码的原意是 先string.c_str(),然后用vector<conse char*>容器保存string.c_str()的首个字符的地址。
#4
peach54602013-08-21 10:59
vector<string> 容器里到底存储的是什么? 是string里第一个字符的地址,还是整个push_back进去的字符串的副本?
你觉得是什么?自己写段代码测试一下啊
系统处理字符串,就是把字符串当成字符指针处理吗?
自己写代码测一下
我的代码的原意是 先string.c_str(),然后用vector<conse char*>容器保存string.c_str()的首个字符的地址。
代码逻辑有问题
1