【发布时间】:2017-02-24 17:43:34
【问题描述】:
好的,当我尝试下面的代码时,我正试图找出一个问题:
#include <iostream>
#include <vector>
#include <stdint.h>
#include <string>
#include <Windows.h>
using namespace std;
int main(){
vector<char*> v;
char s[10];
std::cout << "Enter Values :\n";
for (int i = 0; i<5; i++){
cin >> s;
v.push_back(s);
}
std::cout << "\n\n\nPrinted Values :\n";
for (auto ss : v){
cout << ss << "\n";
cout << "------------\n";
}
system("pause");
return 0;
}
这是我收到的输出:
Enter Values :
aaaa
ssss
ddddd
ffff
errrr
Printed Values :
errrr
------------
errrr
------------
errrr
------------
errrr
------------
errrr
------------
但现在我把“char*”改成了“string”:
#include <iostream>
#include <vector>
#include <stdint.h>
#include <string>
#include <Windows.h>
using namespace std;
int main(){
vector<string> v;
string s;
std::cout << "Enter Values :\n";
for (int i = 0; i<5; i++){
cin >> s;
v.push_back(s);
}
std::cout << "\n\n\nPrinted Values :\n";
for (auto ss : v){
cout << ss << "\n";
cout << "------------\n";
}
system("pause");
return 0;
}
现在,它将所有数据存储到向量中:
Enter Values :
aaaa
ssss
ddddd
ffff
errrr
Printed Values :
aaaa
------------
ssss
------------
ddddd
------------
ffff
------------
errrr
------------
我的问题是,为什么 char* 没有存储在向量中,而字符串却存储在向量中?
【问题讨论】:
-
char*只是一个指针,而std::string是一个类。数组不会自动复制。
标签: c++ string for-loop vector char