我想創建一個向量,它應該輸入strings (white space included)
,直到用戶輸入'!'
。創建一個字符串矢量:C++
下面是我的代碼:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
int main()
{
char buffer[100];
string temp;
vector <string> vec;
while(1)//Shows Segmentation fault error while running,
//compiles succesfully
{
cout << "Enter String : ";
cin.get(buffer,100,'\n');//To ensure that whitespaces are also input
cout << "@@@@ " << buffer << endl ;//Shows correct input
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
//Clearing cin stream for any residual characters
temp.assign(buffer);//Assigning string the input "phrase"
cout << "###" << temp << endl;//Shows correct output
if (temp == "!") //if input is '!' character do not push on the vector a
//come out of the loop
break;
vec.push_back(temp);//push on the vector
temp.assign(NULL); //flush temp string
}
vector <string>::iterator p = vec.begin();
//display thre vector
while(p != vec.end())
{
cout << *p << endl;
p++;
}
return 0;
}
它編譯成功,但在運行時拋出Segmentation fault
錯誤。
無法弄清楚爲什麼?有人可以指出嗎?
此外,更智能的解決方案,讚賞一邊指出我的代碼有什麼問題。
感謝
只需使用'std :: getline'來讀取帶有空格的字符串即可。您不需要施加不必要的最大長度,或擔心您的長度與您的緩衝區大小相匹配。 – chris 2013-05-04 18:40:03