I have written a C++ Function which can be represented as below:
All it does is take a string (this is where it crashes) and reverse it.
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
cout<<"Enter a string: "<<endl;
char *str;
gets(str);
cout<<"Reversed String is: ";
for(int i=strlen(str)-1;i>=0;i--)
cout<<(str[i]);
return 0;
}
I guess there's some kind of memory access violation.
Any clue why this doesn't work?
Error: Segmentation fault (core dumped)
In c++ there is way more easier and less error prone solution to this problem via std::reverse from algorithm. Also its easier to use std::string.
#include <iostream>
#include <algorithm>
int main ()
{
std::string input;
std::cout << "Enter string to reverse: ";
std::cin >> input;
std::reverse(input.begin(),input.end());
std::cout << "Reversed string: " << input << std::endl;
return 0;
}
If you have to do it via char arrays, try this (you dont even need dynamic memory allocation)
#include <iostream>
#include <algorithm>
#include <cstring>
int main ()
{
char input[1024];
puts("Enter string to reverse: ");
fgets(input, 1024, stdin);
std::reverse(input, input + strlen(input));
printf("Reversed string: %s", input);
return 0;
}
Your code isn't c++ style and I recommend you take a look at the answer from Filip (https://stackoverflow.com/a/45903067/4386427)
I'll just address what goes wrong with your code.
When you do
char* str;
all you get is a pointer that can point to a char. You don't get any memory for holding a char. Further the value of the pointer variable str is uninitialized.
So when you do
strlen(str)
you read an uninitialized variable and try to treat this uninitialized value as a C-style string. That is undefined behavior and is very likely to cause a program crash.
You need to make sure that str is initialized before using it. As you want dynamic memory, you could do:
char *str;
str = new(char[100]); // Initialize str to point to a dynamic allocated
// char array with size 100
...
...
delete(str);
But again - I wouldn't use this style in c++ code
Related
I am trying to limit user input into alphabet only, then sort all the character in ascending order.
build messages
error: no matching function for call to 'std::__cxx11::basic_string::basic_string(char&)'
This is my header
#include <iostream>
#include <string.h>
#include <conio.h>
#include <stdio.h>
#include <regex>
should i convert the char into string then convert back to char for my following code ?
string Sortstr (str[mlength]);
sort(Sortstr.begin(), Sortstr.end());
getting this 2 line error.
int mlength = 100;
int main() {
char str[mlength];
int length;
cout << "Please enter a c-string: ";
cin.getline(str,mlength,'\n');
regex pass1("^[a-zA-Z]+");
while(!regex_match(str,pass1)) {
cout<<"Error"<<endl;
cout << "Please enter a c-string: ";
cin.getline(str,mlength,'\n');
}
string Sortstr (str);
sort(str, str + strlen(str));
}
Why not just sort str?
sort(str, str + strlen(str));
There's no reason you can't sort an array directly. Just pass pointers to the first and one-past-the-end elements of your array to sort. In this case adding strlen gets a pointer to the effective end of your array.
In this line
string Sortstr (str[mlength]);
you are using the index operator on a char array which gives you one single char. So, you are passing one single char to the string constructor. This constructor does not exist, hence the error. Even if it existed, you do not want to pass one single char but the entire char array.
What you want is this:
string Sortstr (str);
I was trying to hold the text entered by user inside an Char array but it does not end up well. I tried this method but i think it deleted after c++ 11.
Here's my code :
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char sentence[2];
cout << "Enter your sentences : ";
gets_s(sentence);
cout << sentence << endl;
system("PAUSE");
return 0;
}
It gives overload error and doesnt works.
Chances are you are trying to get the string literal that is longer than 2 characters yet not being able to insert it into your buffer of:
char sentence[2];
Increase the buffer size to something more acceptable:
char sentence[255];
That being said in C++ you should prefer std::string to character array and std::getline to gets_s.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "hello";
reverse(begin(s), end(s));
cout << s << endl;
return 0;
}
prints olleh
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s[5] = {"hello"};
reverse(begin(s), end(s));
cout << *s << endl;
return 0;
}
prints hello
Please help me understand why is such difference. I am newbie in c++, I am using c++ 11.
Ok, I corrected to s[5]={"hello"} from s[5]="hello" .
The first is a single string. The second is an array of five strings, and initializes all five string to the same value. However, allowing the syntax in the question is a bug (see the link in the comment by T.C.) and should normally give an error. The correct syntax would have the string inside braces, e.g. { "hello" }.
In the second program you are only printing one string of the five anyway, the first one. When you dereference an array, it decays to a pointer and gives you the value that pointer points to, which is the first element in the array. *s and s[0] are equivalent.
I think that what you are looking for is this:
int main() {
char s[] = "hello";
reverse(s, s + (sizeof(s) - 1));
cout << string(s) << endl;
return 0;
}
With char[6] you have an C-style string. Remember that theses strings must be terminated with '\0'. Therefore there is a 6th element.
I'm trying to make a program that reads in a "string" (into a char *) from user input, then using cstring, it gets the length of what the char * is pointing to. From what I understand, char * is a pointer. A reference to a pointer will be redirected to what it is pointing to. In this case, word should point to 4321, and when word gets output, what it is pointing to is what actually gets output. Also, strlen should read up until the \0, which in this case the string should be 4321\0, so why does it segmentation fault?
Desired result:
Enter a string: 4321
4321
(length of 4321)
Program:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char *word;
int len;
cout << "Enter a string: ";
cin >> word;
len = strlen(word); //why does this cause a segmentation fault?
cout << word << endl;
cout << len << endl;
return 0;
}
You need
char word [256] ; // or something
Better yet
std::string word ;
cout << word.length () ;
In your code "word" is just a pointer. If you mean to write something directly into a pointer, first you must assign a valid memory address to it. If it is not important for you that "word" is a pointer then a char array will suffice.
I was trying to write a program that stores the message in a string backwards into a character array, and whenever I run it sometimes it successfully writes it backwards but other times it will add random characters to the end like this:
input: write this backwards
sdrawkcab siht etirwˇ
#include <iostream>
#include <string>
using namespace std;
int main()
{
string message;
getline(cin, message);
int howLong = message.length() - 1;
char reverse[howLong];
for(int spot = 0; howLong >= 0; howLong--)
{
reverse[spot] = message.at(howLong);
spot++;
}
cout << reverse;
return 0;
}
The buffer reverse needs to be message.length() + 1 in length so that it can store a null termination byte. (And the null termination byte needs to be placed in the last position in that buffer.)
Since you can't declare an array with a length that is only known at runtime, you have to use a container instead.
std::vector<char> reverse(message.length());
Or better, use std::string. The STL also offers some nice functions to you, for example building the reversed string in the constructor call:
std::string reverse(message.rbegin(), message.rend();
Instead of reversing into a character buffer, you should build a new string. It's easier and less prone to bugs.
string reverse;
for(howlong; howLong >= 0; howLong--)
{
reverse.push_back(message.at(howLong));
}
Use a proper C++ solution.
Inline reverse the message:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message;
getline(cin, message);
//inline reverse the message
reverse(message.begin(),message.end());
//print the reversed message:
cout << message << endl;
return 0;
}
Reverse a copy of the message string:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message, reversed_message;
getline(cin, message);
//reverse message
reversed_message = message;
reverse(reversed_message.begin(), reversed_message.end());
//print the reversed message:
cout << reversed_message << endl;
return 0;
}
If you really need to save the reversed string in a C string, you can do it:
char *msg = (char *)message.c_str();
but, as a rule of thumb use C++ STL strings if you can.