printing a char array backwards c++ using loops - c++

i am trying to print an array of unknown length backwards so wrote that the loop should start at the terminator and go to the first letter printing each letter but it keeps printing only the first
#include <iostream>
using namespace std;
int main()
{
char word[10];
int i;
cout << "Enter a word: " ;
cin >> word;
for ( word[i]= '\0'; word[1] <0; word[i] --)
{
cout << word[i] << endl;
}
return 0;
}

You can print you C-style string backwards whith this one-liner:
reverse_copy(word,word+strlen(word),ostream_iterator<char>(cout));
Also please consider using std::string:
string word;
cin >> word;
copy(word.rbegin(),word.rend(),ostream_iterator<char>(cout));
You will need to #include the following headers for the above examples to work:
<algorithm>, <iostream>, <iterator>, <string> and <cstring>

Replace your loop it does nothing:
for (i= strlen(word); i >=0; i--)
{
cout << word[i] << endl; //endl is optional
}
Also for in case of long strings you may have to increase size of char array or its better to use
string word;
for (i= word.size(); i >=0; i--)
{
cout << word[i] << endl; //endl is optional
}

Here is a simple way to print a C-style string backwards.
for (size_t i = 0, i_end = std::strlen(word); i != i_end; ++i)
{
std::cout << word[i_end - i - 1];
}
std::cout << "\n";
Note that I save the result of strlen so that it is not called every time.

To get the result you want, you might want to use this code...
char word[10];
int sz;
do {
cout << "Enter a word: ";
cin >> word;
sz = strlen(word);
} while (sz > 10);
for (int i = sz; i >= 0; i--)
{
cout << word[i];
}

Related

Compare char with char[i] not working in hangman game

I was trying to do a hangman game, my idea was that you give the number of letters and the word, then the program fills a char with _ as letters the word has. Then it asks you a letter and it compares if the letter matches any letter in the word given. Then it replaces the respective _ with the letter, but it doesn't replace it...
What am I doing wrong?
#include <iostream>
#include <conio.h>
#include <cstdlib>
using namespace std;
int main()
{
int game = 0;
int n = 0;
char blank[n - 1];
char palabra[n - 1];
char letra;
cout << "Input the number of letters of the word\n";
cin >> n;
cout << "Input the word\n";
cin >> palabra;
for (int i = 0; i < n; i++) {
blank[i] = '_';
}
while (game != 1) {
for (int i = 0; i < n; i++) {
if (letra == palabra[i]) {
blank[i] = letra;
}
else {
if (blank[i] != '_') {
blank[i] = blank[i];
}
else {
blank[i] = '_';
}
}
}
system("cls");
cout << "\n";
for (int i = 0; i < n; i++) {
cout << blank[i] << " ";
}
cout << "Input a letter" << endl;
cin >> letra;
}
getch();
return 0;
}
int n = 0;
char blank[n - 1];
There are three things wrong with this:
The n is initialized to 0, but then the array will have 0 - 1 length.
The value of n isn't really known until it is input by the user, but you went ahead and declared blank with n-1 entries.
Even if n were initialized to something reasonable, the declaration of
char blank[n - 1];
is not legal C++ syntax. Arrays in C++ must have their size denoted by a compile-time constant, not a runtime variable.
To get rid of these issues, use std::string instead of char arrays.
If you did that, the code would look similar to this:
#include <string>
#include <iostream>
int main()
{
int game = 0;
int n = 0;
std::string palabra;
char letra;
std::cout << "Input the number of letters of the word\n";
std::cin >> n;
std::cout << "Input the word\n";
std::cin >> palabra;
std::string blank(n, '_'); // create a string with n underscores
//...
}
The rest of the code should stay the same. Whether the overall logic of the program is correct, that would be another issue, but at least you do not have the issue with the character arrays.

Stuck on removing whitespace from string without using any helper code c++

Create a program titled str_compress.cpp. This program will take a sentence input and remove all spaces from the sentence. (A good first step in encryption programs) Make sure that both the input and output strings are all stored in a single variable each. Do not use numbers or symbols. Include both upper-case and lower-case letters. Account for cases with multiple spaces anywhere.
This is what I have so far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0, j = 0, len;
string str;
cout << "Enter string: ";
getline(cin, str);
len = str.length();
for (i = 0; i < len; i++)
{
if (str[i] == ' ')
{
for (j = i; j < len; j++)
{
str[j] = str[j + 1];
}
len--;
}
}
cout << str << endl;
system("pause");
return 0;
}
I can eliminate spaces, but only one at a time. If I copy and paste the for loop, I can remove all spaces for how many loops there are. I'm thinking that I can loop the for loop over and over until all spaces are gone, but I'm not sure how to do that. Also, I can't use anything like remove_all() or erase().
This is a strong clue for how the authors of your exercise want you to write your code:
Make sure that both the input and output strings are all stored in a single variable each
You should make a new string:
string new_str;
Use your loop over the input string. For each char in the string, check whether it is a space. If yes, do nothing. If no, append it to the output string:
for (i = ...)
{
char c = str[i];
if (c != ' ')
new_str.push_back(c);
}
Your loop's logic when removing a space is wrong. For instance, after removing a space, you then skip the next char in the string, which may be another space. Also, although you are decrementing the len, you don't resize the string to the new len before printing the new str value.
It should look more like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
size_t i, j, len;
string str;
cout << "Enter string: ";
getline(cin, str);
len = str.length();
i = 0;
while (i < len)
{
if (str[i] == ' ')
{
for (j = i + 1; j < len; ++j)
{
str[j - 1] = str[j];
}
--len;
}
else
++i;
}
str.resize(len);
cout << str << endl;
/* or, if you are not allowed to use resize():
cout.write(str.c_str(), len);
cout << endl;
*/
/* or, if you are not allowed to use write():
if (len < str.length())
str[len] = '\0';
cout << str.c_str() << endl;
*/
system("pause");
return 0;
}
Live Demo
However, your instructions do say to "Make sure that both the input and output strings are all stored in a single variable each", which implies that separate std::string variables should be used for input and output, eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
size_t i, j, len;
string str, str2;
cout << "Enter string: ";
getline(cin, str);
str2 = str;
len = str2.length();
i = 0;
while (i < len)
{
if (str2[i] == ' ')
{
for (j = i + 1; j < len; ++j)
{
str2[j - 1] = str2[j];
}
--len;
}
else
++i;
}
str2.resize(len);
cout << str2 << endl;
/* or:
cout.write(str2.c_str(), len);
cout << endl;
*/
/* or:
if (len < str2.length())
str2[len] = '\0';
cout << str2.c_str() << endl;
*/
system("pause");
return 0;
}
Live Demo
Alternatively:
#include <iostream>
#include <string>
using namespace std;
int main()
{
size_t i, j, len;
string str, str2;
cout << "Enter string: ";
getline(cin, str);
len = str.length();
str2.reserve(len);
for(i = 0; i < len; ++i)
{
char ch = str[i];
if (ch != ' ')
str2 += ch;
}
cout << str2 << endl;
system("pause");
return 0;
}
Live Demo
This is what worked for me. Thank you everyone for the help!!
int main()
{
int i, j, len;
string str, str2;
cout << "Enter string: ";
getline(cin, str);
len = str.length();
for (i = 0; i < len; ++i)
{
char ch = str[i];
if (ch != ' ')
str2 += ch;
}
cout << str2 << endl;
system("pause");
return 0;
}

How to move word in a circular motion in a string?

I have a string that contains X words (between each word there is a space) I have to move the words in a circular motion to the left according to the number that the user inserts. For example:
"hi my name is aviv and",
the user entered 2. "name is aviv and hi my" I'm looking for legality that repeats itself but I can not find.
Thanks for the guidance. Most importantly, I can not use built-in libraries
Update:
I see there are examples with libraries, I can not use any library.
So what I've done so far.
I wrote a function that gets a string and a number from the user, to move left.
Before sending the string to the function I try to calculate the number of characters I need to move.
My output is - "name is avivhi my"
Regarding the function:
When it gets a string without spaces it works great.
This is my code:
int main()
{
char str[] = "hi my name is aviv";
char str2[] = "hi my name is aviv";
int CountSpace = 0, CountWord = 0;
int Size = 18, flag = 0;
int MoveLeft, Index = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
CountSpace++;
}
}
CountWord = CountSpace + 1;//Understand how many words there are in a string.
cin >> MoveLeft;
if (MoveLeft >= CountWord)//
{
MoveLeft = (MoveLeft - ((MoveLeft / CountWord) * CountWord));//the size of movment;//To reduce the amount of moves if there is such a possibility
}
for (int i = Size - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
flag++;
}
if (flag == MoveLeft)
{
Index = Size - 1 - (i + 1);//That's the amount of characters I have to move
break;
}
}
MoveLeft = Index;
//This code belongs to the function that accepts a string and the amount to move the characters
for (int i = 0; i < Size; i++)
{
if (i + MoveLeft < Size)
{
str[i] = str2[i + MoveLeft];
}
else
{
str[i] = str2[(i + MoveLeft) - Size];
}
}
cout << "Move Left: " << MoveLeft << endl << str << endl << str2 << endl;
return 0;
}
Here's a hint:
vector<string> words = Your_Code_To_Split_Input_Into_Words();
int count = words.size();
int shift = Your_Code_To_Read_Users_Input();
// print the sentence with the rotation specified by shift
for (int i = 0; i < count; i++)
{
int shifted_index = (i + shift) % count; // modulo math implements circular rotation
string spacing = (i == 0) ? "" : " "; // add a space before each word, except first word
cout << spacing << words[shifted_index];
}
cout << endl;
One possible answer, i highly recommend using vectors instead of regular arrays, it's easy and more dynamic, but i didn't use it because you said you can't use built-in libraries.
#include <iostream>
#include<string>
using namespace std;
int main() {
string a[10000];
int counter = 0;
string b = "hi my name is aviv and";
string temp = "";
int userNum = 2;
for(int i=0;i<b.length() ; i++){
if(b[i]!=' '){
temp+=b[i];
}
else if(b[i]==' ' && temp.length()){
a[counter]= temp;
temp = "";
counter++;
}
}
if(temp.length()){
a[counter] = temp;
}
for(int i=userNum;i<=counter+userNum;i++){
cout<<a[i%(counter+1)]<<endl;
}
}
If you can make use of std::rotate() from <algorithm>, this is much easy to do with that. Parse the words using std::stringstream and store to std::vector. Then apply the shif directly to the vector.
Sample Output: https://www.ideone.com/rSPhPR
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
int main()
{
std::vector<std::string> vec;
std::string str = "hi my name is aviv and";
std::string word;
std::stringstream sstr(str);
while(std::getline(sstr, word,' '))
vec.emplace_back(word);
int shift;
std::cout << "Enter the Shift: ";
std::cin >> shift;
std::rotate(vec.begin(), vec.begin() + shift, vec.end());
for(const auto& it: vec)
std::cout << it << " ";
return 0;
}
Here's a snippet :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MaxWords 10
int main()
{
stringstream ss;
ss.str("hi my name is aviv and");
string str[MaxWords];
int i;
for (i =0; std::getline(ss, str[i],' ');i++ )
{
cout << str[i] << " ";
}
int n;
cout << "\nEnter pos to split : ";
cin >> n;
for (int j = n; j <= i; j++)
{
cout << str[j] << " ";
}
for (int j = 0; j < n; j++)
{
cout << str[j] << " ";
}
cout << endl;
return 0;
}
Output:

why does my counter increase according to the lens of char input in C++

I'm picking up on C++ recently and is trying to code a program which prompts for names for a defined no. of times and inserts each of the input into an array of size-5. The problem happened when I tried to run the following code, my counter, i increases according to the no of len the user input. Why is that so?
#include <iostream>
using namespace std;
int main(){
const int SIZE = 5;
char name[SIZE];
int i;
for (i = 0; i < SIZE; i++){
if (strlen(name) <= 50) {
cout << "Enter a name: \n";
cin >> name[i];
}
}
for (i = 0; i < SIZE; i++){
cout << name[i] << endl;
}
return 0;
}
Output:
if (strlen(name) <= 50) {
You should not call strlen on array which is not initialized.
Use array of strings otherwise
cout << name[i] << endl;
refers to i-th character, not entire string. Or if you want to go with char arrays, you'd need a two dimensional array.
I thing what you indended to do was :
#include <iostream>
using namespace std;
int main(){
const int SIZE = 5;
string names[SIZE];
int i;
for (i = 0; i < SIZE; i++){
cout << "Enter a name: \n";
string name;
cin>>name;
if (strlen(name) <= 50) {
cin >> names[i];
}
}
for (i = 0; i < SIZE; i++){
cout << name[i] << endl;
}
return 0;
}
UNTESTED
The second for loop, which does the output, does this in single characters, incrementing i each time.
To output the string all at once assign a string pointer to name[0] and send that to cout.

Storing Chars Into Strings in C++

So right now I have this code that generates random letters in set increments determined by user input.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int sLength = 0;
static const char alphanum[] =
"0123456789"
"!##$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
int main()
{
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
while(true)
{
for (int x = 0; x < sLength; x++)
{
cout << genRandom();
}
cout << endl;
}
}
I'm looking for a way to store the first (user defined amount) of chars into a string that I can use to compare against another string. Any help would be much appreciated.
Just add
string s(sLength, ' ');
before while (true), change
cout << genRandom();
to
s[x] = genRandom();
in your loop, and remove the cout << endl; statement. That will replace all of the printing by putting the characters into s.
Well, how about this?
std::string s;
for (int x = 0; x < sLength; x++)
{
s.push_back(genRandom());
}
#include<algorithm>
#include<string>
// ...
int main()
{
srand(time(0)); // forget me not
while(true) {
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
string r(sLength, ' ');
generate(r.begin(), r.end(), genRandom);
cout << r << endl;
}
}