C++ :String reversal not working? - c++

I am having trouble understanding the output I am getting for this piece of code
#include<iostream>
#include<stdio.h>
using namespace std;
int main() {
int i = 0;
int j = 0;
int k = 0;
char ch[2][14];
char re[2][14];
cout << "\nEnter 1st string \n";
cin.getline(ch[0], 14);
cout << "\nEnter the 2nd string\n";
cin.getline(ch[1], 14);
for(i = 0; i < 2; i++) {
int len = strlen(ch[i]);
for(j = 0, k = len - 1; j < len; j++, k--) {
re[i][j]=ch[i][k];
}
}
cout << "\nReversed strings are \n";
cout << re[0];
cout << endl << re[1] << endl;
return 0;
}
for example
/*
Input :
hello
world
Output :
olleh<some garbage value>dlrow
dlrow
*/
Sorry if it very basic, but I can't understand the reason. Thanks in advance.

Make sure that re[0] and re[1] are null-terminated
For example during initialization you could do
for (int i = 0; i < 14; i++)
{
re[0][i] = '\0';
re[1][i] = '\0';
}
But aside from that I suggest to used std::string and std::reverse and the like.

for (i = 0; i < 2; i++)
{
int len = strlen(ch[i]);
for (j = 0, k = len - 1; j < len; j++, k--)
{
re[i][j] = ch[i][k];
}
re[i][len] = '\0';
}
you have to terminate your reversed strings.
also you should #include <string.h> for the strlen() function.

You forgot about the terminating zero for strings in array re Simply define the array the following way
char ch[2][14] , re[2][14] = {};
^^^^
Also take into account that you should remove header <stdio.h> because it is not used and instead of it include header <cstring>.
This task can be done with using standard algorithm std::reverse_copy
For example
#include <iostream>
#include <algorithm>
#include <cstring>
int main()
{
const size_t N = 2;
const size_t M = 14;
char ch[N][M] = {};
char re[N][M] = {};
std::cout << "\nEnter 1st string: ";
std::cin.getline( ch[0], M );
std::cout << "\nEnter the 2nd string: ";
std::cin.getline( ch[1], M );
std::cout << std::endl;
for ( size_t i = 0; i < N; i++ )
{
std::reverse_copy( ch[i], ch[i] + std::strlen( ch[i] ) , re[i] );
}
for ( const auto &s : re ) std::cout << s << std::endl;
return 0;
}

Related

what is the issue with this char reverse function?

so I wrote this code to reverse one of the names based on the user option the idea is to use another function to reverse and to use pointers but after trying all I could think of my code return the same name not changed the best I could do was changing the first letter of the name to a weird sign.
#include <iostream>
using namespace std;
void reverse(char* A) {
int count = 0;
char temp[10];
for (int i = 0; A[i] != NULL; i++)
count++;
for (int i = 0; A[i] != NULL; i++) {
temp[count]=A[i];
count--;
}
for (int i = 0; A[i] != NULL; i++) {
A[i] = temp[i];
}
}
int main(){
int x= 0;
int index;
char Name_list[5][10];
cout << "please enter the names of the student " << endl;
for (int i = 0; i < 5; i++) {
cin >> Name_list[i];
for (int j = 0; Name_list[i][j] != NULL; j++) {
x++;
}
while (x > 10)
{
x = 0;
cout << "you have entered more then the allowed number of characters per name enter another name " << endl;
cin >> Name_list[i];
for (int j = 0; Name_list[i][j] != NULL; j++) {
x++;
}
}
x = 0;
}
for (int i = 0; i < 5; i++) {
cout << Name_list[i] << endl;
}
cout << "please enter the index of the name you want to reverse" << endl;
cin >> index;
while (index>4||index <0)
{
cout << "you entered incorrect index please enter a number from 0 to 4 " << endl;
}
reverse(Name_list[index]);
for (int i = 0; i < 5; i++) {
cout << Name_list[i] << endl;
}
system("pause");
}
For starters such a function should return a pointer to the result string. That is it should be declared like
char * reverse( char *s );
Note: do not use variable names consisting from upper case letters.
The type int can be not large enough to store length of a string. Instead use the type size_t.
char * reverse( char *s )
{
size_t count = 0;
//...
It is totally unclear why there is present an array with the number of elements equal to the magic number 10
char temp[10];
To reverse a string there is no need to declare an auxiliary array. Such an approach is principally wrong.
In this for loop
for (int i = 0; A[i] != NULL; i++)
there is compared an object of the type char with the pointer NULL. The compiler should issue a message for such a wrong comparison. It seems you mean
for (int i = 0; A[i] != '\0'; i++)
In any case the introduced variable i in this first for loop is redundant because you already has the variable count.
As you have the array temp with the fixed size equal to 10 then the both loops after the first loop can invoke undefined behavior even if the length of the source string is equal exactly to 10.
And the result string is not zero terminated.
The function can look the following way.
char * reverse( char *s )
{
size_t count = 0;
while ( s[count] ) ++count;
for ( size_t i = 0; i < count / 2; i++ )
{
char c = s[i];
s[i] = s[count - i - 1];
s[count - i - 1] = c;
}
return s;
}
Or using standard functions you could write the function reverse the following way
#include <utility>
#include <cstring>
//...
char * reverse( char *s )
{
for ( size_t i = 0, n = std::strlen( s ); i < n / 2; i++ )
{
std::swap( s[i], s[n-i-1] );
}
return s;
}
Pay attention to that there is the standard algorithm std::reverse. Using it you could reverse a string the following way
std::reverse( s, s + std::strlen( s ) );
for (int i = 0; A[i] != NULL; i++) {
temp[count]=A[i];
count--;
}
If i goes up from 0 to 5, count goes down from 6 to 1.
Ok, a few things.
If you want do some string manipulation, look into the stdlib. Unless you are doing this for class.
Your writing everything to the end of the temp. buffer
You need to add an extra character at the end of the strings for the null byte (I think this implementation may allow for a seg. fault)

Why is my loop not returning the right answer?

I can't figure it out. What is wrong with my code? I am new to programming.
Program required output: Write a C++ program to find the maximum-occurring character in an array, using a loop.
My code:
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
index = Word[i];
}
}
cout << index << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,100);
FindMaxChar(Word);
}
My Output:
Enter the Word = caaar
r is repeating 11 times.
You never reset count each loop. So you continue incrementing it but never clear it.
Add count = 0 to the beginning of the outer for loop:
for (int i = 0; i < length; i++)
{
count = 0; // Reset counter
You're also trying to use index for two different purposes. You're both using it to store the current character you're looking at (not an index, kind of confusing that you named it like that), AND the character you've seen the most (still not an index, also confusing).
Instead, you need another variable here.
Also note that if you declare Word as char Word[100], it can only hold a c-string of length 99 (to leave room for the null character). So your cin should actually be:
cin.get(Word, 99);
Thanks to the great people of this community.
I am able to find my error and corrected it.
Correct Code :
#include <iostream>
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
char final = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
count = 0;
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
final = index;
}
}
cout << final << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,99);
FindMaxChar(Word);
}

how to create an array of Bitset in c++

I want to create an array of Bitset .Binary Bitset(example "100","1010",etc)
After that I want to input from user and store in the the Bitset .
I have tried the following line but it says error.
#include<bits/stdc++>
using namespace std;
int main()
{
int n,i;
string bit_string;
cin>>n // size of Bitset array.
bitset<8> brr[n];//
for(i=0;i<n;i++)
{
cin>>bit_string;
brr[i](bit_string);
}
return 0;
}
I want to create n Bitset each of size 8 bits.Where n is given by user.
my input is binary string like.
"110010","001110"
please help
The error ocurrs because you are trying to creat a C-style array using n which is not compile-time constant. It's not possible to creat a C-style array without being n known at compile time.
The following is a good way to do what you want
Creat a std::vector<std::bitset<8>> to hold your bitset<8>s, as follows.
Note that the code ignores the excess of characters in strings iput like "111111110" (makes it "11111111") and treats any character except '1' as if it were '0' and if the input string is less than 8 characters, the code adds zeros by the default of the bitsets
#include <vector>
#include <bitset>
#include <iostream>
int main() {
int n, i;
std::string bit_string;
std::cout << "Enter the size";
std::cin >> n; // size of Bitset array.
std::vector<std::bitset<8>> brr(n);//
for (i = 0; i < n; i++) {
std::cin >> bit_string;
for (int j{}; j < bit_string.size() && j < 8; ++j) {
brr[i][j] = (bit_string[j] == '1') ? 1 : 0;
}
}
//To test
for(auto const& el :brr)
{
for(int i{}; i < 8;)
std::cout << el[i++];
std::cout<<"\n";
}
}
See Why is "using namespace std;" considered bad practice?
and
Why should I not #include <bits/stdc++.h>?
For dynamic count of the objects , Please try vector<> instead of array[]
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
vector<bitset<8>> arr; //size()=>0
arr.resize(n); //size()=>n
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
return 0;
}
If you still want to use array , please try this way
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
bitset<8>* arr = new bitset<8>[n];
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
delete[] arr; //IMPROTAND , delete the array and free memory
return 0;
}

Placing Random String values into an int Array

I am pretty newish at c++ and was wondering how I can place values randomly into an int array.What I want to do is use this function to place into a grid randomly for the purpose of creating a memory matching game.
#include "stdafx.h"
#define NOMINMAX
#include <iostream>
#include <iomanip>
#include <windows.h>
#include <time.h>
#include <string>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
void shuffleL(int [][8]);
int main()
{
//shuffles characters
shuffleS(charactersS);
for (int i = 0; i <= 8; i++)
{
cout << "---";
}
cout << endl;
//output grid
for (int r = 0; r < 4; r++)
{
cout << r + 1 << " | ";
for (int c = 0; c < 4; c++)
{
cout << " [VGC] ";
status[r][c] = false;
}
cout << endl;
}
cout << endl;
}
void shuffleL(int characters[][8])
{
string vgc[50] = { "PacMan", "Laura", "Mario", "Sonic", "Link", "Snake", "Drake", "Samus", "MegaMan", "Kratos",
"Isaac", "DK", "Dante", "Crash", "Spyro", "Kirby", "Ryu", "Yoshi", "Sora", "Strider",
"DigDug", "Lil_Mac", "Pit", "Booker", "Rayman", "Frogger", "Marcus", "Shepard", "Sly", "Ezio",
"Guybrush", "Leon", "Raz", "Ninten", "Ralph", "Crono", "MaxPayne", "Fox", "Simon", "Cole",
"Pheonix", "Corvo", "Parappa", "Faith", "Lucas", "Scorpion", "Gordon", "Roland", "Chell", "Olimar" };
string temp;
for (int s = 0; s <= 4; s++)
{
for (int x = 0; x<16; x++)
{
srand((unsigned)time(NULL));
int i = rand() % 15 + 1;
temp = vgc[x];
vgc[x] = vgc[i];
vgc[i] = temp;
}
}
int i = 0;
//Input of Values in Here
for (int r = 0; r < 50; r++)
{
for (int c = 0; c < 50; c++)
{
characters[r][c] = vgc[i]; //THIS VGC GIVES ME THE ERROR
cout << characters[r][c];
i = i + 1;
}
cout << endl;
}
}
It also gives me an error for one of the variableNames (vgc) saying
1 IntelliSense: no suitable conversion function from "std::string" to "int" exist
I am completely stumped on how to fix this solution.
Dont do int characters [] [8]; , but string characters [] [8]; . The type you specify at the start of the array declaration is the type of info the array will store.
Peace.
The problem is, you are trying to store string in your int type array.
for (int c = 0; c < 50; c++)
{
characters[r][c] = vgc[i]; //<- **Here**
cout << characters[r][c];
i = i + 1;
}

C++ - Adding Spaces to String

Hey so I am trying to write a simple program that adds spaces to a given string that has none in C++ here is the code I have written:
#include <iostream>
#include <string>
using namespace std;
string AddSpaceToString (string input)
{
const int arrLength = 5;
int lastFind = 0;
string output;
string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};
for (int i = 0; i < input.length(); i++)
{
for (int j = 0; j < arrLength; j++)
{
if(dictionary[j] == input.substr(lastFind, i))
{
lastFind = i;
output += dictionary[j] + " ";
}
}
}
return output;
}
int main ()
{
cout << AddSpaceToString("heywhatshelloman") << endl;
return 0;
}
For some reason the output only gives hey whats and then stops. What is going on I can't seem to make this very simple code work.
After reading "hey" and "whats", the value of i is more than the length of "hello" and hence no such substring exists for the code input.substr(lastFind, i).
You should check for the length of possible substring (dictionary[j]) and not i.
input.substr( lastFind, dictionary[j].size() )
Also you will have to change:
lastFind += dictionary[j].size();
So the if loop becomes:
if(dictionary[j] == input.substr(lastFind, dictionary[j].size() ))
{
lastFind += dictionary[j].size();
output += dictionary[j] + " ";
}
this works
#include <iostream>
#include <string>
using namespace std;
string AddSpaceToString (string input)
{
const int arrLength = 5;
unsigned int lastFind = 0;
string output;
string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};
for (int j = 0; lastFind < input.size() && j < arrLength; ++j)
{
if(dictionary[j] == input.substr(lastFind, dictionary[j].size()))
{
lastFind += dictionary[j].size();
output += dictionary[j] + " ";
j = -1;
}
}
return output;
}
int main ()
{
cout << AddSpaceToString("heywhatshelloman") << endl;
return 0;
}