Segmentation fault in reversing string program - c++

I am trying to reverse a string. Can someone explain me why this is giving me segmentation fault?
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
int len=str.length(),i=0;
cin>>str;
while(str[i]!='\0'){
rstr[--len]=str[i++];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}
P.S.: Need to reverse it without using library functions.

If you want to go the way you are doing it, for practice purposes, try this changes and start from there
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
cin>>str; // --- Moved this line up
rstr = str; // --- Added this line
int len=str.length(),i=0;
while(str[i]!='\0'){
rstr[--len]=str[i++];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}

Or just use reverse iterator
std::string s = "Hello";
std::string r(s.rbegin(), s.rend());

str is nothing but a declared string here:
int len=str.length(),i=0;
So you can't do str.length()
Do something like:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
int len,i=0;
cin>>str;
len = str.length();
while(str[i]!='\0'){
rstr[i++]=str[--len];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}

Related

I'am working on a C++ program where I'am facing a error while execution of if-else statement [duplicate]

#include <iostream>
using namespace std;
int main() {
char word[10]="php";
char word1[10]="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
I don't know how to compare two char strings to check they are equal. My current code is not working.
Use strcmp.
#include <cstring>
// ...
if(std::strcmp(word, wordl) == 0) {
// ...
}
Use std::string objects instead:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word="php";
string word1="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
To justify c++ tag you'd probably want to declare word and word1 as std::string. To compare them as is you need
if(!strcmp(word,word1)) {
word and word1 in your submitted code are pointers. So when you code:
word==word1
you are comparing two memory addresses (which isn't what you want), not the c-strings they point to.
#include <iostream>
**#include <string>** //You need this lib too
using namespace std;
int main()
{
char word[10]="php";
char word1[10]="php";
**if(strcmp(word,word1)==0)** *//if you want to validate if they are the same string*
cout<<"word = word1"<<endl;
*//or*
**if(strcmp(word,word1)!=0)** *//if you want to validate if they're different*
cout<<"word != word1"<<endl;
return 0;``
}

getting segmentation fault string s=s+"A";

CASE 1
If i use
string s=s+"A" i get segmentation fault
#include <iostream>
#include <string>
using namespace std;
int main() {
string s=s+"A";
return 0;
}
CASE 2
but if i use
string s;
s=s+"A" it works fine
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
s=s+"A";
return 0;
}
what is the reason of segmentation fault in case 1.
Also had it been any other datatype like int it works fine.
string s hasn't been initialized here yet:
string s=s+"A";
This is why you are getting a segmentation fault.
In the second case:
string s; // default value ""
s = s+ "A"; // you are getting "" + "A"

conversion string to character in c++ Not Working Properly

make a function which receive the file name but it not working properly because it receives "Doctor.txtG" but I am giving "Doctor.txt" how can i resolve it?My code is Given below......
#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
int number_of_lines = 0;
int numberoflines(string A);
int main()
{
cout<<numberoflines("Doctor.txt");
getch();
return 0;
}
int numberoflines(string A)
{
int Len;
char Chr[Len];
Len=A.length();
A.copy(Chr, Len);
//cout<<Len;
cout<<Chr;
string line;
ifstream myfile(Chr);
if(myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile,line);
number_of_lines++;
}
myfile.close();
}
return number_of_lines;
}
It needs to copy a null-terminated byte into Chr.
Use
strcpy(Chr, A.c_str());
instead of A.copy(Chr, Len);
And you should properly init Chr like
char Chr[1024]
or
char* Chr = new char[Len + 1].
Your problem is happening because you are trying to create a char array with the size Len. But you have not initialized Len before using it. This is why it is resulting in undefined behavior and creating this problem. Always try to initialize variables when you declare them. Otherwise, this problem will happen quite often.
However, You don't need to create another char array. Just use std::string::c_str(); in your parameter for the constructor of the ifstream. I am giving a sample code below. This should solve your problem.
#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
int number_of_lines = 0;
int numberoflines(string A);
int main()
{
cout<<numberoflines("Doctor.txt");
getch();
return 0;
}
int numberoflines(string A)
{
string line;
ifstream myfile(A.c_str());
if(myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile,line);
number_of_lines++;
}
myfile.close();
}
return number_of_lines;
}

Sorting a string using STL

I am trying to sort the characters of a string using C++ STL and came up with this code.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main()
{
using namespace std;
vector<string>::iterator it;
string arr[] = {"jajajaj"};
vector<string> v(arr, arr+2);
sort(v.begin(), v.end());
for (it=v.begin(); it<v.end(); it++) {
cout << *it;
}
return 0;
}
But unfortunately its not sorting properly when the array contains single element. How to do it using STL.
Please help.
You can sort the string using std::string class.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
string str = "jajajaj";
sort(str.begin(), str.end());
cout << str;
return 0;
}
Hope this might be helpful.
If you need a string, use a std::string :
(I used a for-range loop to make the code cleaner)
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string s = {"jajajaj"};
sort(s.begin(), s.end());
for (auto c : s)
cout << c;
return 0;
}
Outputs:
aaajjjj
Note:
Your current code is not working because, as commented, you create a vector of size 2 out of an array of size 1, which has undefined behavior.
You seem to be confusing a std::string with an array of chars.
int main()
{
using namespace std;
string arr = "jajajaj";
vector<char> v(arr.begin(), arr.end());
sort(v.begin(), v.end());
vector<char>::iterator it;
for (it=v.begin(); it<v.end(); ++it) {
cout << *it;
}
return 0;
}
I haven't tested that, but it should work....
UPDATE:
Alternately, we could just sort the string's character directly: (Thanks guys!)
int main()
{
using namespace std;
string arr = "jajajaj";
sort(arr.begin(), arr.end());
cout << arr;
return 0;
}
You can use sort() function. sort() exists in algorithm header file
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string str = "sharlock";
sort(str.begin(), str.end());
cout<<str<<endl;
return 0;
}
Output:
achklors
In order to sort a string, just input string from the user and use the sort() in STL for it.
#include<bits/stdc++.h>
using namespace std;
int main()
{
string arr;
cin >>arr;
sort(arr.begin(), arr.end());
cout <<arr;
}
See the sample image below for the output with input string as "Michael".

How to compare char variables (c-strings)?

#include <iostream>
using namespace std;
int main() {
char word[10]="php";
char word1[10]="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
I don't know how to compare two char strings to check they are equal. My current code is not working.
Use strcmp.
#include <cstring>
// ...
if(std::strcmp(word, wordl) == 0) {
// ...
}
Use std::string objects instead:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word="php";
string word1="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
To justify c++ tag you'd probably want to declare word and word1 as std::string. To compare them as is you need
if(!strcmp(word,word1)) {
word and word1 in your submitted code are pointers. So when you code:
word==word1
you are comparing two memory addresses (which isn't what you want), not the c-strings they point to.
#include <iostream>
**#include <string>** //You need this lib too
using namespace std;
int main()
{
char word[10]="php";
char word1[10]="php";
**if(strcmp(word,word1)==0)** *//if you want to validate if they are the same string*
cout<<"word = word1"<<endl;
*//or*
**if(strcmp(word,word1)!=0)** *//if you want to validate if they're different*
cout<<"word != word1"<<endl;
return 0;``
}