c++ - I am getting a segmentation fault in this code and can't understand why? -


i trying code program takes program input , prints out comments written in program in separate line.

#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std;   int main() {     string str;      while(getline(cin,str))    {     int i;        // cout<<str;      for(i=0;str[i]!='/' && str[i+1] !='/';i++);         //cout<<i;     for(i;str[i]!='\n';i++) {        // cout<<i;         cout<<str[i];     }         cout<<endl;      }     return 0; } 

i getting segmentation fault in code , can't understand why. part of code of problem in hackerrank https://www.hackerrank.com/challenges/ide-identifying-comments/copy-from/12957153

as commented in question code wrong. first treating std::string object, returned getline, character array. secondly loops never end if there no // or \n found in input string. crash. below modified code.

#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std;   int main() {     string str;      while(getline(cin,str))    {     int i;        // cout<<str;      size_t len = str.length();     const char *cstr = str.c_str();     for(i=0; (cstr[i]!='/' && cstr[i+1] !='/' && < len); i++)         //cout<<i;     for(; cstr[i]!='\n' && < len;i++) {        // cout<<i;         cout<<cstr[i];     }         cout<<endl;      }     return 0; } 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -