Vector動態數組字符類型-整行輸入
問題描述
我們在字符串輸入的時候,如果要輸入一行字符,就直接用std::cin
就可以,但是如果要輸入hello world呢?就要用到getline()整行輸入,getline或cin.getline的詳細介紹見前面的鏈接。
但是,我們用vector的char類型動態數組怎麼整行輸入呢?我們知道,C語言中沒有string類型,字符數組就是字符串,可以用cin.getline(ch, 500)
這種方式整行輸入,但vector不支持getline,下面詳細介紹。
解決方法
1.自己寫函數
沒有函數庫,就自己寫函數庫嘛,對不😄
如果我們用c++開發,先定義一個string字符串,然後先用string的getline(std::cin, str);然後再建立一個函數讀入字符數組,然後遍歷字符串,把每一個字符push_back()進字符數組,就成了,見下面代碼
2.
代碼
Solution
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void vectorSetValue(vector<char>&aVec, string aStr){
for (int i=0; i< aStr.size(); i++){
aVec.push_back(aStr[i]);
}
}
void showVector(vector<char>&aVec){
for (int i=0; i< aVec.size(); i++){
cout << aVec[i];
}
}
int main(){
vector <char> s1;
string s2;
getline(cin, s2);
vectorSetValue(s1, s2);
showVector(s1);
return 0;
}
showVector(s1);
return 0;
}