0

I am getting segmentation fault while running my cpp program?What can be the reason?

#include <iostream> bool leapyear(int year) { if(year%4==0) { return true; }else if(year%4!=0) { return false; } } int main() { int y = 2016; //std::cin >> year; if(leapyear(y)==true) { std::cout<<y+" is leap year" << std::endl; }else if(leapyear(y)==false) { std::cout <<y+" is not a leap year" << std::endl; } return 0; } why i am getting segfault ?i don't think i am overwriting any file i am not allowed to ?

28th Sep 2017, 3:21 PM
shobhit
shobhit - avatar
2 Respuestas
+ 7
I think the error is due to the statements cout<< y + "is leap year"; and cout<<y + "is not a leap year"; , as we cannot add strings and integers in C++ directly... As a correction, try the following function - std::to_string(int); // C++11 only... Or, convert 'y' to a string using stringstream using the following function : std::string to_str(int a) { stringstream ss; ss<<a; return ss.str(); } Here is the code, corrected , using std::to_string. #include <iostream> #include <string> bool leapyear(int year) { if(year%4==0) { return true; }else if(year%4!=0) { return false; } } int main() { int y = 2016; //std::cin >> year; if(leapyear(y)==true) { std::cout<<std::to_string(y)+" is leap year" << std::endl; }else if(leapyear(y)==false) { std::cout <<std::to_string(y) +" is not a leap year" << std::endl; } return 0; }
28th Sep 2017, 3:43 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 4
or #include <iostream> bool leapyear(int year) { if(year%4==0) { return true; }else if(year%4!=0) { return false; } } int main() { int y = 2016; //std::cin >> year; if(leapyear(y)==true) { std::cout<<y << " is leap year" << std::endl; }else if(leapyear(y)==false) { std::cout <<y << " is not a leap year" << std::endl; } return 0; } without conversion
28th Sep 2017, 3:46 PM
Andrea Simone Costa
Andrea Simone Costa - avatar