Printing words vertically - c++

So I'm just starting in C++, so I'm not familiar with the language, though I do have knowledge of C. I'm trying to print words vertically. Here is the problem given.
Create an array of 25 strings.
Use a sentinel loop that reads from cin until the array is full or the end of input is reached
(when the user presses Ctrl-D), whichever comes first.
After the sentinel loop is over, use a for loop to move through the array.
Remember not to travel farther than the last array element that was input.
Print one array element (one string) followed by a newline
Use a for loop to move through the characters of the string you just printed
print one character followed by a newline
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
char word;
int count = 0;
cout << "Enter a word: (press Ctrl-D to quit)";
cin >> word;
int array1[25];
while (!cin.eof())
{
count = count + 1;
cout << "Enter a word: (press Ctrl-D to quit)";
cin >> word;
} //end while
for (word = 0; word <= array1[count]; word++)
{
cout << 'end1' << 'end1' << "There were " << count << "Words Entered" << 'end1';
}
} //end main
Code is rough, it compiles, but when it is in an infinite loop with numbers comes out after the texts.

Just for the hell of it
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
int main() {
string word;
int count = 0;
vector<string> arrayOfStrings;
cout << "Enter a word: (press Ctrl-D to quit)";
while(cin >> word){
if(count < 25){
arrayOfStrings.push_back(word);
count = count + 1;
cout << "Enter a word: (press Ctrl-D to quit)";
} else {
cout << "25 strings was entered";
break;
}
}//end while
for ( int j = 0; j < arrayOfStrings.size(); j++ ){
cout << '\n' << '\n' << $j << "-st string entered " << arrayOfStrings[j] << '\n';
}
}//end main
This code reads exactly 25 strings, remembers them, and even outputs them later.
This is just an educational example, which basically ignores memory managment
I strongly suggest not to use this in any actual code.
It took me about 5 mins to write this.

There are a few errors in this code - perhaps if you are familiar with C, then quickly write a version in C and translate it to a more modern "C++ like" version. Perhaps look into std::string and std::vector to make life even easier.
int array1[25]; needs to store strings, therefore it is of the wrong type.
The while (!cin.eof()) loop needs to also check that it doesn't go over the bounds of the above array (i.e. at most 25 words).
The for (word = 0; word <= array1[count]; word++) loop that needs to loop exactly n times, where n is the number of words inputted, i.e. in the above while loop.

Related

input stream with string

If I type john when prompted for a char, the while statement will loop 4 times, one for each letter of john, before it asks again for user input.
Why does this program do not allow me insert more input before the whole 4 chars of john are consumed ? I would expect it to discard the 3 remaining letters of the string john and asked me for more input on the second loop.
The whole example can be found at page 44 of Bjarne Stroustrup The C++ Programming Language 4th edition.
#include <iostream>
using namespace std;
bool question() {
while (true) {
cout << "Continue ?\n";
char answer = 0;
cin >> answer;
cout << "answer: " << answer << endl;
}
return false;
}
int main () {
cout << question() << endl;
}
The output becomes:
Continue ?
john
answer: j
Continue ?
answer: o
Continue ?
answer: h
Continue ?
answer: n
Continue ?
You may be wondering why you're not being allowed to enter a character at each prompt. You have entered four characters into the input stream, so your loop runs four times to consume all of that input.
If you only want to use the first character in the input, you may want to get an entire line and work on just the first character.
#include <iostream>
#include <string>
bool question() {
while (true) {
std::cout << "Continue ?\n";
std::string line;
std::getline(std::cin, line);
std::cout << "answer: " << line[0] << endl;
}
return false;
}
Of course, you should also check that an empty line was not entered, which may be as simple as checking if line[0] is not '\0'.

Stack program to enter names and reprint in C++

So this program that I have is a stack program that is to let a business owner enter the names of clients. I have an error on the loop where it's supposed to push names onto the stack, which I feel may have something to do with the fact that I used stoi. Any thoughts?
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
stack<string> name;
cout << "Welcome to Carl's Cab Stand!!" << endl;
cout << endl;
string input;
while (input != "Stop") //Loop to enter names
{
cout << "Enter the names of your clients for today (Enter 'Stop' when finished): " << endl;
cin >> input;
}
int x = stoi(input); //Convert int/string
for (int y = 0; y < x; x++) //Loop to push names onto stack
name.push(y);
while (!name.empty()) //Loop to print names
{
cout << name.top() << endl;
name.pop();
}
cin.get();cin.get();
return 0;
}
I think there are some bugs in your code.
In your while-loop you always overwrite the variable input with your latest input. And in your case it will always be "Stop".
Then if you use stoi, on the variable input with the value "Stop", what should it return?
It also seems that there are problems with the for loop: (int y = 0; y < x; x++)
you increment x with each iteration. so if x is positive it will run until an overflow will occure.
The error you will receive may happen because of this line:
name.push(y);
The stack is for strings. y is an integer. So I Thin this would lead to an error.
So check your program again and think about how it could work.
regards
Andi

Permutation Issue

So I have a program here that is supposed to print to the screen permutations of a user input word that can be 4 to 10 characters long and there are supposed to be as many permutations as there are letters in the word. I almost have complete success, but there is one issue. When it prints the permutations, after the first about 2 permutations, it starts to not use all the letters and/or the same letter twice.
For example, if the user input word is "bill", the output is as follows:
llib illb ibll lbii
The fourth is is obviously not correct. The problem is more apparent with words that have more letters. I need it to only use the letters it has once. How do I go about fixing this in my code? Here is my code.
int main(void)
{
string word;
string randword;
string reverse;
int length;
int i = 0;
int j = 0;
string randCH;
cout << "Enter any word 4 to 10 letters in length: ";
cin >> word;
//Checks if word is less than 4 or greater than 10
while (1)
{
/*The code here is in the final program and I know it works. The problem is not here*/
}
length = word.length();
//Uses reverse function
reverse = reverseit(word);
/*reverseit is a function outside of main that makes the word backwards*/
//Prints all permutations
cout << endl << reverse << " ";
for (i = 0; i < word.length() - 1; i++)
{
for (j = 0; j < word.length(); j++)
{
randCH = word.substr(rand() % length, 1);
cout << randCH;
}
cout << " ";
cout << endl;
you can use std::next_permutation which is already built to achieve this:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string word;
cin >> word;
sort(word.begin(),word.end());
do {
cout << word <<endl;
} while(next_permutation(word.begin(),word.end()));
}

C++ Issue with cin and CTRL + Z

I'm reading c++ primer 5th and I have a little problem with an exercise:
Read a sequence of words from cin and store the values a vector. After
you’ve read all the words, process the vector and change each word to
uppercase. Print the transformed elements, eight words to a line.
My code is this:
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main(){
vector<string> words;
string wordBuffer;
vector<string> output(1);
while (cin >> wordBuffer){
words.push_back(wordBuffer);
}
for (string &word : words){
for (char &letter : word){
letter = toupper(letter);
}
}
unsigned currentLine = 0;
for (decltype(words.size())index = 0; index < words.size(); ++index){
output[currentLine] += words[index] + " ";
if ((index+1) % 8 == 0){
++currentLine;
output.push_back("");
}
}
for (string s : output){
s[s.size() - 1] = 0; //removing the whitespace
cout << s << endl;
}
system("pause");
return 0;
}
Now, everything works well, but i have an issue with the input of the words by console.
If I write
I am writing a random words ^Z
and press Enter nothing happens. I have to rewrite the ^Z after I have pressed the Enter, like here:
I am writing a random words
^Z
Can you expain me why? Thanks!
PS: I'm saying that because in my previous programs writing ^Z in the same line worked fine. Like in this code:
#include <iostream>;
int main(){
int currval = 0,val = 0;
int count = 1;
while (std::cin >> val){
if (currval == val){
++count;
}
else {
std::cout << "The number " << currval << " appears " << count << " times" << std::endl;
currval = val;
count = 1;
}
}
std::cout << "The number " << currval << " appears " << count << " times" << std::endl;
system("pause");
return 0;
}
I can't figure out why :(
The ^Z has to be first in order for Windows to treat it as Ctrl+Z, otherwise it is just treated as meaningless characters.
If you would like it to work like you wrote i'd suggest:
String wordBuffer("")
while (strcmp(wordBuffer[strlen(wordBuffer)-3], "^Z") != 0){
words.push_back(wordBuffer);
cin >> wordBuffer
}
EDIT: in your second example it works because when you read integers c++ knows to divide the given string of numbers in the space (or ENTER if the numbers are entered separately in every line) to read every number separately so if you'll enter:
123 2323 4545 43 ^Z
It will read 123, then 2323, ... and then ^Z and so it will be as though it got it in a separate line but when you read string, it cant do that because a string contain every symbol and so it separate the input in the ENTER pressed and that why the second one works
As far as I know Ctrl+Z is placed in the keyboard buffer before any other entered symbols. Thus any entered characters before Ctrl+Z will be discarded. You need to do the following
I am writing a random words ENTER
^Z ENTER

Recognize "010" and similar numbers as a palindrome using modulus in C++

First post! This is my second semester with "Advanced C & C++" so any help is GREATLY appreciated. I've already scoured as much of stackoverflow and a few other resources to try and help me understand what I'm doing (or not doing) with this slew of logically inept code.
The goal of this program is to recognize whether or not a 'number' given by the user is a palindrome. Sounds simple enough right?! Ugh...well this is what I have been stuck on:
#include <iostream>
using std::cout;
using std::cin;
#include <string>
using std::string;
#include <cstdlib>
int main()
{
//variable declarations
string buffer;
//user input
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
//looooop
while(buffer != "Q" && buffer !="q")
{
int userNum, length, sum = 0, temp;
userNum = atoi(buffer.c_str());
for(temp = userNum; userNum !=0; userNum=userNum/10)
{
length = userNum % 10;
sum = sum*10+length;
}
if(temp==sum)
cout << temp << " is a palindrome!!\n\n";
else
cout << buffer << " is NOT a palindrome!\n\n";
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
}
}
The problem arises when input of "010", or "400" is given. "400" is essentially "00400" in this case and both should be seen as a palindrome.
A better approach would be to get trailing zeros for the given number as below:
int noOfTrailingZeros = str.length;
while(str[--noOfTrailingZeros]=='0');
noOfTrailingZeros = str.length - noOfTrailingZeros;
Or the integer way as:
int noOfTrailingZeros = str.length;
while(num%10==0)
{
noOfTrailingZeros++;
num/=10;
}
Now, check for the input string whether it has the same number of zeros befire the number or not as:
int counterZeros = 0;
while(str[counterZeros++]=='0');
check these 2 numbers and if trailing zeros are more than the zeros at beginning, add that many at the beginning and pass that string to palindrome function.
First of all, to recognize a palindrome, you don't have to do atoi. Just pass from the start to the middle checking if
buffer[i] == buffer[length - i]
Second, use the atoi to make sure it is a number and you're done.
Other way is to compare the string with itself reversed:
string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}