我正在尝试创建一个strings (white space included)
在用户输入之前应该输入的向量'!'
。
下面是我的代码:
#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
错误。
无法弄清楚为什么?任何人都可以指出吗?
对此也有更聪明的解决方案,同时指出我的代码有什么问题。
谢谢