它看起来像我cout*cp,它只输出字符串的第一个字母,在我把它们放在矢量后,我的输出是空白的.我究竟做错了什么?
//write a program to assign the elements from a list of char* pointers to c-style character strings to a vector of strings
#include <iostream>
#include <cstring>
#include <vector>
#include <list>
#include <string>
using namespace std;
int main ()
{
list<const char*> clist;
cout<<"please enter a string"<<endl;
for(string s; getline(cin,s); )
{
const char* cp=s.c_str();
clist.push_back(cp);
cout<<*cp;
}
cout<<*clist.begin();
vector<string> svec;
svec.assign(clist.begin(),clist.end());
for(vector<string>::iterator iter=svec.begin(); iter!=svec.end(); ++iter)
cout<<*iter<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这将打印整个字符串:
cout << cp; // You're providing cout a const char *
Run Code Online (Sandbox Code Playgroud)
这只会打印一个字符:
cout << *cp; // You're providing cout a char
Run Code Online (Sandbox Code Playgroud)
至于你的向量有什么问题,你只存储指向字符串的指针,而不是字符串本身.字符串的内存超出了范围.正如其他人所说,使用std::string而不是原始const char *.
| 归档时间: |
|
| 查看次数: |
2048 次 |
| 最近记录: |