Reversing characters from input - c++

I am trying to reverse a char which has been provided in input from an user. I am having issues with the reverse function, particularly the loop. I can't get it to work- can I get advice?
#include <iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char temp[len];
for(int i=len; i>len; --i) {
temp[i]+=input[i];
}
return temp;
}
int main()
{
char input[100];
while(cin>>input) {
cout << reverse(input);
}
return 0;
}

Your Program has few issues
You're trying to return local variable address i.e. temp array address. The Function will return the address to main function. Since memory might get cleaned so it will print garbage value present at the address.
As Rohan Bari mentioned variable length array might cause undefined behavior. There for you can create a constant length array i.e.
char temp[100];
or you can dynamically allocate array on heap. Memory allocated on heap do not get cleared after termination of block but we have to manually delete it.
char* temp = new char[len];
As array start from 0 it goes till len-1 so loop condition should start from len-1 and has to go till 0 to reverse.
+ operator do not work's with array or char even if you are trying to add just char it preforms normal integer addition of their ASCII value.
Here is improved version of your code
#include<iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char* temp = new char [len]; // or you can use char temp[100];
int j = 0; //temp variable to enter values from 0th index if we use same as loop it just enter in the same order as original char array.
for(int i=len-1; i>=0; --i) {
temp[j++] = input[i];
}
temp[j] = '\0';
return temp;
}

You have got several errors in the program.
The variable-length arrays are used here:
char temp[len];
This should not be applied in C++ since this invokes undefined-behavior. Note that this is a valid statement in the C99 standard.
There is a better alternative to this. That is to take the std::string built-in type in use.
In the following line:
temp[i] += input[i];
You are not sequentially adding one character after another, but the values of them in a single integer. This could be not a problem if temp was of the type std::string.
The reverse function should look like this:
const char *reverse(char *input) {
int len = strlen(input);
std::string temp;
while (len--)
temp += input[len];
return temp.c_str();
}

len should actually be (len-1) and i should be >= 0 not len, so from (len-1) to 0 your loop should run.
for(int i = len-1; i >= 0; i--){}

You have to allocate the new array with the new keyword if you don't want to use a string. The following code does what you need:
char* reverse(char* input)
{
int len = strlen(input);
char* temp = new char[len + 1];
for (int i = len; i >= 0; --i)
{
temp[len-i-1] = input[i];
}
temp[len] = '\0';
return temp;
}

You could use a std::stack to reverse your input:
std::stack<char> s;
char c;
while (std::cin >> c)
{
s.push(c);
}
while (!s.empty())
{
std::cout << s.top();
s.pop();
}

It's 2021. Use the STL. If your instructor isn't aware of it or doesn't allow you to use it, your instructor is not keeping up-to-date and you should fire your instructor.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string input{};
while(std::getline(std::cin, input)) {
std::reverse(std::begin(input), std::end(input));
std::cout << input << '\n';
}
return 0;
}

There's quite many things wrong with the code as many people have already mentioned! Since you want to implement this without using STL it can be done this way,
#include <iostream>
using namespace std;
#include <cstring>
void reverse(char* input,int len) { //added len as argument
char temp[len];
for(int i=len-1; i>=0; --i) {
temp[len-i-1]=input[i];
cout<<temp[len-i-1]; //printing while reversing
}
cout<<endl;
}
int main()
{
char input[100];
int len=0;
//using do while since it has to run atleast once
do{
cin.getline(input,100);
len=strlen(input);
input[len]='\0';
if(len!=0)
reverse(input,len);
}while(len!=0) ;
return 0;
}

Related

How can I convert an char array to string without dealing with the string as an array

int main() {
char arr[10] = {};
string str;
arr[0] = 'h';
arr[1] = 'e';
arr[2] = 'y';
for (int i = 0; i < 10; i++) {
str[i] = arr[i];
}
cout << str;
}
Why this code is not printing hey?
I didn't forget to include the libraries I just put the important part of the code.
when I try to cout str[1] as an example it cout 'e' but when I try to cout the string as it is it doesn't print anything.
I apologize in advance if my explanation is a bit vague but you forgot to include the <iostream> and <string> libraries in your header. Also, since you are using the string library, you must include the using namespace std; within the scope of your string str;. There is a bit more optimization that you can do to your code. For example, in this case, it is optimal to iterate up to the size of your array instead of iterating through to 10 as most of your array is empty. Also, because you are adding char values to a string object, you can just concatenate the empty string with the value at arr[i].
#include <iostream>
#include <string>
int main ()
{
using namespace std; //must include this as string object requires it
char arr[10];
string str;
arr[0]='h';
arr[1]='e';
arr[2]='y';
for (int i = 0; i < sizeof(arr); i++)
{
str += arr[i]; //adds arr[i] to the end of str
}
cout << str; //prints string
}
I hope this helps and was clear enough!

How should I convert an increasing number array into a character array so that I can use the atoi function

#include<stdio.h>
#include <string>
#include <stdint.h>
#include<sstream>
#include <stdlib.h>
using namespace std;
string IntToString(int&);
int main()
{
char output[45] = "0";
int str = 0;
char enc[8] = "0";
int enc1[1] = { 0 };
int arrayLength = sizeof(enc1) / sizeof(enc1[0]);
string strs;
for (int i = 0; i <= 100000; i++)
{
int enc1[1];
enc1[0]={ i };
for (int i = 0; i < arrayLength; i++)
{
int& temp = enc1[i];
strs+= IntToString(temp);
enc == strs.c_str();
}
if (atoi(enc)+46*2 == 3251)
{
output == enc;
}
}
printf("%s", output);
}
string IntToString(int& i)
{
string s;
stringstream ss(s);
ss << i;
return ss.str();
}
This is what I want to convert an integer array into a string by continuously increasing, and then convert the string into a number according to the atoi function as a function,I've looked at tutorials on using stoi and I'm not sure what I'm doing wrong. I would appreciate it if you could help me
You code has a lot of problems...
As for your question, if you want to convert an integer into a string, just use std::string your_string = std::to_string(you_integer);.
Then some of the problems that you have:
enc == strs.c_str(); <- the operator == is not the assignment operator. What you do here is that you compare two pointers, that is probably not what you intended, because you don't even check the result of the comparison.
Don't use the loop index i in a nested loop when it is already in use.
Don't use char arrays in C++ unless you have an explicit reason to use it. Even if you are worried about performance, for small strings you can look at std::string as a char array. And you cannot have large strings, because the largest possible integer value represented as a string still counts as a small string.
If you have arrays with constant size, use #define ARRAY_SIZE 15 or something like this rather than what you did.
Don't pass primitive types by reference if you don't have to. As far as I know, only double and long long are larger (on most platforms) than a reference, so you won't gain anything from passing by reference. On the contrary, the optimizer won't like you if you use unnecessary aliasing.
I have to say, I am not sure that I understood your goal correctly. But as I understood it, you want to convert an integer array into a string then to an integer. I am not quiet sure why you would want to do that, but that's on me.
The following code does what I think you wanted. It converts an integer array into an integer by first converting it into a string. But even so, you cannot increase the array size much, because std::stoi will throw an std::out_of_range exception when the number in the string would be too large for an integer.
#include <string>
#include <iostream>
#define ARRAY_SIZE 9
int int_arr_to_int (const int * const arr) {
std::string str;
for (size_t i = 0; i < ARRAY_SIZE; ++i) {
str += std::to_string(i);
}
return std::stoi(str);
}
int main(int argc, char* argv[]) {
int arr[15] = { 0 };
for (size_t i = 0; i < ARRAY_SIZE; ++i) {
arr[i] = i;
}
std::cout << int_arr_to_int(arr) << std::endl;
return 0;
}

Reversing string using stack (static array) in c++

i am new to this concept in c++
i am trying to reverse string using stack static array implementation in c++.
Input: qwerty
expected output: ytrewq
output which i am getting is: trewq
Can some one explain me why is this happening and any possible solution.
Here's my code
#include <iostream>
#include <string>
using namespace std;
#define SIZE 10
string arr[SIZE];
unsigned a = -1;
void push(char ch) {
a = a + 1;
arr[a] = ch;
}
void pop() {
a = a - 1;
}
void display() {
for (int j = a; j >= 0; j--)
cout << arr[j];
}
int main() {
string str;
getline(cin, str);
for (int i = 0; i < (str.length() - 1); i++)
push(str[i]);
display();
}
Remove the "-1" in :
for(int i=0;i<(str.length())-1;i++)
Else your array doesn't contains the last character.
I made the test without the -1, it works well.
The condition "< str.length()" is enough to loop on all string caracter.
In similar case, use the debugger to see what contains your variable. In these case the variable "arr" don't contains the last input caracter.
You push everything on the stack, so the last element can be popped first. Then do popping to fill a reversed strng. The stack should be a char array.
As this is typically a task, the rest is your puzzle.
Pop typically gives you the top element as:
char pop() {
char ch = arr[a];
--a;
return ch;
}
The correct way to reverse a string would be to do:
std::reverse(str.begin(), str.end());
But I think this might be homework/study so look at your output. You are just missing the last letter. That suggests the upper limit of your loop is wrong doesn't it?

How modify character arrays inside functions?

I want to update a character array by reversing it. The character array is correct when output inside function, but not in main after the function is called.
I believe that the character array is passed by reference, but when updating the array, the character array in the main function is not updated. What am I doing wrong here?
#include <iostream>
#include <cstring>
using namespace std;
void StringReverse(char *ch, int size){
char sh[100] = {0};
for(int i=0 ; i<size ; i++){
sh[i] = ch[size-1-i];
}
sh[size] = '\0';
ch = sh;
cout<<ch<<endl;
}
int main(){
char ch[100];
cin.getline(ch, 100);
int size = strlen(ch);
StringReverse(ch,size);
cout<<ch;
}
I do not want to print the result inside the function, but update the character array 'ch' in the main function by calling the function StringReverse.
You want to use strncpy() instead of ch = sh;. As other people have kindly pointed, you are not modifying ch. You are modifying the local variable sh only.
#include <iostream>
#include <cstring>
using namespace std;
void StringReverse(char *ch, int size){
char sh[100] = {0};
for(int i=0 ; i<size ; i++){
sh[i] = ch[size-1-i];
}
sh[size] = '\0';
strncpy(ch, sh, 100);
cout<<ch<<endl;
}
int main(){
char ch[100];
cin.getline(ch, 100);
int size = strlen(ch);
StringReverse(ch,size);
cout<<ch;
}
The ch in StringReverse function is local to that function. And that's why when assign ch = sh;, it doesn't change the ch in main.
While you can copy sh, a better approach is to use reverse in-place so that you wouldn't need a local copy at all.
For example:
void StringReverse(char *ch, int size){
for(int i = 0, j= size - 1 ; i < j ; i++, j--){
int t = ch[i];
ch[i] = ch[j];
ch[j] = t;
}
cout << ch << endl;
}
If you use std::string instead of a plain char array, it would be a lot easier to do this. You could for example use std::reverse.

Reversing the sequence of a string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
A fairly simple program, trying to reverse the characters in a null terminated string in C++, but something seems to be going wrong.
#include <iostream>
using namespace std;
void reverse(char*);
int main(){
char *str;
cout<< "Please enter a string, no spaces please..";
cin >> str;
//reverse(str);
}
void reverse(char *str){
char temp;
size_t len = strlen(str);
for (size_t i = 0; i < len/2; i--)
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
Getting the following error
Bus error: 10
Any help appreciated.
Allocate memory for str before use char *str = new char[25];
In reverse function for for loop increment i for (size_t i = 0; i < len/2; i++ )
Deallocate memory after use delete [] str ;
You are decrementing iterator i insted of incrementing it. A little bit compact version of yours:
#include <algorithm>
#include <cstring>
void reverse(char* const str)
{
unsigned long const len = strlen(str);
for(unsigned long i = 0; i < len >> 1; i++)
std::swap(str[len - i - 1], str[i]);
}
#include <algorithm>
#include <string>
#include <iostream>
#include <cstring>
int main() {
// You can't read something to nowhere.
// String will be holded in static array.
char str[1024];
// To keep it as null terminated string after
// writing of inputed string: `std::cin` don't
// write null character after writing of data.
memset(str, 0, 1024);
std::cin >> str;
// If you do reversing of strings in C++,
// you shouldn't use hand written loops:
std::reverse(str, str + strlen(str));
std::cout << str << std::endl;
}
Try this modified version of your code:
#include <iostream>
#include <cstring>
using namespace std;
void reverse(char*);
int main(){
char str[1024]; // buffer of 1024 chars
cout<< "Please enter a string, no spaces please..";
cin >> str;
reverse(str);
cout << "\nReversed: " << str;
}
void reverse(char *str){
char temp;
size_t len = strlen(str);
for (size_t i = 0; i < len/2; i++) // loop until half of the user input
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
I simply added the array of char char str[1024]; to store the user input.. and changed the loop to: for (size_t i = 0; i < len/2; i++)
However, you must be very careful with the above code.. it works properly if the size of the input is less than the array fixed size.