I want to reverse a char string in c++.
I wrote this code:
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80];
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l; i < l-1; i++, j--){
word[j] = rev[i];
}
cout << rev << endl;
return 0;
}
In terminal it shows some characters like this:
83???uH??? ... Something like this
Your character array rev is not zero terminated.
And istead of to write to rev you are writing to word.:)
word[j] = rev[i];
The loop is also wrong due to condition
i < l-1;
There must be
i < l;
The program can look the following way
#include <iostream>
#include <cstring>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
size_t i = 0;
for ( ; i < n; i++ ) rev[i] = word[n - i - 1];
rev[i] = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
The program output is
polymorphism
msihpromylop
Take into account that you can do the same using standard algorithm std::reverse_copy declared in header <algorithm>.
For example
#include <iostream>
#include <cstring>
#include <algorithm>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
*std::reverse_copy( word, word + n, rev ) = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
The program output is the same as above
polymorphism
msihpromylop
There are 3 changes I made to your code:
Change 1: Since string length is l, indexing will be from 0 t ol-1.
Change 2: rev will be storing the values from word, not the other way round.
Change 3: A proper string should be \0 terminated.
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80]="";
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l-1; i < l; i++, j--){ //change 1
rev[i] = word[j]; // change 2
}
rev[i]='\0'; // change 3
cout<<rev;
return 0;
}
Working ideone link: http://ideone.com/kIqeNF
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80] = {'\0'};
int i = 0;
int last = strlen(word) - 1;
while(last >= 0) {
rev[i] = word[last];
i++;
last--;
}
cout << rev << endl;
return 0;
}
Related
This question is not about where to put the srand function.
I have just started learning DSA with Insertion Sort. I have written a C++ program to perform Insertion Sort and wanted to create some neat visuals of the Time Analysis. I tried generating Random Arrays for the Time Analysis using the rand() function but the Arrays generated seem to have a character at the end. The elements in the character array should all be single digit integers like '0' '3' and so on.....
The Main Function of the Program:
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <iomanip>
using namespace std;
int size(char a[]) {
int l = 0;
while (a[l] != NULL) {
l++;
}
return l;
}
void InsertionSort(char arr[]) {
for (int k = 1; k < size(arr); k++) {
char temp = arr[k];
int i = k - 1;
while (i >= 0 && arr[i] > temp) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = temp;
}
}
int main(void) {
//Generate Random Arrays of size snum
for (int k = 1; k < 100; k++) {
int snum = k * 100;
char Array[snum];
srand(time(NULL));
for (int s = 0; s < snum; s++)
{
int no = rand() % 9 + 1;
Array[s] = no + '0';
}
cout << "START\t";
//cout<<"\n"<<Array<<"END\n"; // Character is being Printed at the end........ :-(
clock_t start, end;
start = clock();
InsertionSort(Array);
end = clock();
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
cout << "\"" << fixed << time_taken << setprecision(9) << "\",\"" << 100 * k << "\"" << endl;
}
}
How I Compile and Run the Program:
g++ InsertionSort.cpp
./a.out > InsertionSort.txt
--------------EDIT--------------
Based on the suggestions, I have replaced the Array with a vector. Please provide any further suggestions....
RandomIntVector.cpp
#include "RandomIntVector.h"
#include <random>
#include <vector>
using namespace std;
vector<int> RandomVector(int size){
uniform_int_distribution<> d(1, 1000);
mt19937 gen;
vector<int> Ar;
for(int s=0; s<(size-1); s++)
{
int no = d(gen);
Ar.push_back(no);
}
return Ar;}
InsertionSort.cpp
#include "InsertionSort.h"
#include <vector>
using namespace std;
void InsertionSort(vector<int> arr){
int size=arr.size();
for(int k=1;k<size;k++){
int temp = arr[k];
int i=k-1;
while(i>=0 && arr[i]>temp ){
arr[i+1]=arr[i];
i--;
}
arr[i+1]=temp;
}
}
Main.cpp
#include <iostream>
#include <vector>
#include <chrono>
#include <iomanip>
#include "RandomIntVector.h"
#include "InsertionSort.h"
using namespace std;
int main(void){
//Generate Random Arrays of size snum
for(int k=1;k<100;k++){
vector<int> Array = RandomVector(100*k);
clock_t start, end;
start = clock();
InsertionSort(Array);
end = clock();
double time_taken = double(end - start) /
double(CLOCKS_PER_SEC);
//Print the Time Taken along with the size of the Input
cout<<"\""<<fixed << time_taken << setprecision(9)<<"\",\""
<<100*k<<"\""<<endl;
}
return 0;
}
I have two arrays and I want to count how many elements are same between two arrays.
I try many times but the output is not correct. The correct should be 6 times
but the output is 4 times in the code.
Note: if s1 is "ss" and s2 is "ss", is the result 2
Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main() {
char s1[] = "FOOBART";
char s2[] = "BFORATO";
int flag=0;
for(int i=0, j=0; i < sizeof(s1) && j < sizeof(s2); ) {
if(s1[i] == s2[j]) {
flag++;
i++;
j++;
} else if(s1[i] < s2[j]) {
i++;
} else {
j++;
}
}
cout << flag;
}
All elements of s1 are present in both strings so the output will be equal to the length of s1. Here is the correct code
#include <iostream>
using namespace std;
int main() {
char s1[] = "FOOBART";
char s2[] = "BFORATO";
int count=0;
for (int i=0; i<sizeof(s1)-1; i++) {
for (int j=0; j<sizeof(s2)-1; j++) {
if (s1[i]==s2[j]) {
count++;
break;
}
}
}
cout<<count<<endl;
}
Hope this will help you
solution using stl algorithms:
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
const std::string s1 = "FOOBART";
std::string s2 = "BFORATO";
int count = 0;
auto beg = begin(s2);
for(auto& elm : s1)
{
auto x = find(beg, end(s2), elm);
if(x != end(s2))
{
*x = *beg;//get rid of elment and reduce the range of search.
++beg;
++count;
}
}
std::cout << count;
return 0;
}
I have the following two 2D Arrays of C-Strings. I am trying to copy the first one onto the second using strcpy() function. However, I keep getting the runtime error.
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char word1[3][3] = { "Hello", "Bonjour", "Ni Hao" };
char word2[3][3] = { "Steve", "Pei", "Frank" };
char temp[] = "";
for (int i = 0; i < 3; i++) {
strcpy(temp, word1[i]);
strcpy(word1[i], word2[i]);
strcpy(word2[i], temp);
}
for (int i = 0; i < 3; i++) {
cout << word2[i] << " ";
}
cout << endl;
}
In your code i find several mistake.
your char array word1,word2,temp isn't initialize properly.you need to increase size of array.
in loop you use 3.it will break your output if your word's length become grater than 4.
So here i give you little solution.But its better use user input as a size of array so that any input can match properly.
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char word1[10][10] = { "Hello", "Bonjour", "Ni Hao" };//increase array size to fit word
char word2[10][10] = { "Steve", "Pei", "Frank" };//same here
char temp[10] = "";//same here
for (int i = 0; i < 10; i++) {
strcpy(temp, word1[i]);
strcpy(word1[i], word2[i]);
strcpy(word2[i], temp);
}
for (int i = 0; i <10; i++) {
cout << word2[i] << " ";
}
cout << endl;
}
I am working on creating a simulation of a test that will
1. randomize multiple choice answers
2. display the choices from a) b) c) d)
I have both codes done separately however can I use on for-loop to go about displaying this? Is this the best way to do this? All help is appreciated thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE;
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
}
//separate code for part 2: choices from a-g
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE; i++) {
cout << choices[i] << " ";
}
}
You can iterate over both arrays and stop when smaller will ends
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE; // maybe here should be TEST_SIZE?
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE && i < TEST_SIZE; i++) {
cout << choices[i] << " " << animals[i] << ", ";
}
}
Also, consider that if you want to use fixed-size array, you can use std::array:
#include <array>
std::array<string, TEST_SIZE> animals = {...};
And for shuffling you can use std::shuffle from 'algorithm' header .
I have modified the code from my previous question, and now it looks like this:
//#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <chrono>
#include <cassert>
using namespace std;
const int MAX_SIZE=10000;
const int MAX_STRINGS = 10;
char** strings=new char*[10];
int len;
char* GetLongestCommonSubstring( char* str1, char* str2 );
inline void readNumberSubstrings();
inline const char* getMaxSubstring();
void readNumberSubstrings()
{
cin >> len;
assert(len >= 1 && len <=MAX_STRINGS);
for(int i=0; i<len;i++)
strings[i]=new char[MAX_SIZE];
for(int i=0; i<len; i++)
cin >> strings[i];
}
const char* getMaxSubstring()
{
char *maxSubstring=strings[0];
auto begin = chrono::high_resolution_clock::now();
for(int i=1; i < len; i++)
maxSubstring=GetLongestCommonSubstring(maxSubstring, strings[i]);
cout << chrono::duration_cast <chrono::milliseconds> (chrono::high_resolution_clock::now()-begin).count() << endl;
return maxSubstring;
}
char* GetLongestCommonSubstring( char* string1, char* string2 )
{
if (strlen(string1)==0 || strlen(string2)==0) cerr << "error!";
int *x=new int[strlen(string2)+ 1]();
int *y= new int[strlen(string2)+ 1]();
int **previous = &x;
int **current = &y;
int max_length = 0;
int result_index = 0;
int length;
int M=strlen(string2) - 1;
for(int i = strlen(string1) - 1; i >= 0; i--)
{
for(int j = M; j >= 0; j--)
{
if(string1[i] != string2[j])
(*current)[j] = 0;
else
{
length = 1 + (*previous)[j + 1];
if (length > max_length)
{
max_length = length;
result_index = i;
}
(*current)[j] = length;
}
}
swap(previous, current);
}
delete[] x;
delete[] y;
string1[max_length+result_index]='\0';
return &(string1[result_index]);
}
int main()
{
readNumberSubstrings();
cout << getMaxSubstring() << endl;
return 0;
}
It's still solving the generalised longest common substring problem, and now it's rather fast.
But there's a catch: if a user specifies, say, 3 as a number of strings he's about to enter, and then only actually enters one string, this code waits forever.
How do I change that?
If you read from a file and the number of arguments isn't equal to the number of arguments provided, just print a nice, clean error message to the user.
"Expected 7 arguments, received 3:"
Print out the arguments you found so the user has an idea of what the program is looking at when it spits out the error.
As for human input, I agree with the comments. The program should wait until the user close it or enters all the needed arguments.