Creating a vector of strings : C++ -
i trying create vector should input strings (white space included)
until user enters '!'
.
below code :
#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 whitespaces input cout << "@@@@ " << buffer << endl ;//shows correct input cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); //clearing cin stream residual characters temp.assign(buffer);//assigning string input "phrase" cout << "###" << temp << endl;//shows correct output if (temp == "!") //if input '!' character not push on vector //come out of loop break; vec.push_back(temp);//push on 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; }
it compiles @ run-time throws segmentation fault
error.
not able figure out why ? can 1 point out?
also smarter solution this, appreciated along side pointing out wrong code.
thanks
this cause:
temp.assign(null);
as std::string::assign()
attempt read until null terminator found , dereferencing null
pointer undefined behaviour: in case segmentation fault. use temp.clear()
or create new object on each iteration.
use std::getline()
reads lines including whitespace , avoids having hardcode fixed size array (i.e. buffer[100]
):
std::string line; while (std::getline(std::cin, line) && line != "!") { vec.push_back(line); }
Comments
Post a Comment