它看起來像當我cout * cp時,它只輸出字符串的第一個字母,並且在將它們放入向量之後,我的輸出爲空。我究竟做錯了什麼?char *到字符串向量的列表
//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;
}
http://codereview.stackexchange.com而不是標記,雖然這不是一個真正的CR問題 –
'COUT << * CP;',當你提領了'cp'變量(使用'*'運算符),你從你的字符串得到一個單一的字符。因此,爲了打印整個字符串,你甲肝e傳遞實際的指針,例如:'cout << cp;'。然而,你應該使用'std :: string'而不是*裸指針*。 – jweyrich
是什麼讓你知道你應該使用指針?如果你不熟悉C++,你可能會考慮這個僞規則:「如果你使用的是指針,那麼你就是在做錯了。」 –