This question already has answers here:
How to cin Space in c++?
(8 answers)
Closed last month.
I'm having problems with how to show the numbers of vowels in the string I input in this code I made
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
char str[100];
int a, e, i, o, u, whitespace;
a = e = i = o = u = whitespace = 0;
int k;
cout << "Enter a string: ";
cin >> str[99];
for (k = 0; k < strlen(str); k++)
{
if (str[k] == 'A')
{
a = a + 1;
}
else if (str[k] == 'E')
{
e = e + 1;
}
else if (str[k] == 'I')
{
i = i + 1;
}
else if (str[k] == 'O')
{
o = o + 1;
}
else if (str[k] == 'U')
{
u = u + 1;
}
else if (str[k] == ' ')
{
whitespace++;
}
}
cout << "\nVowels:\n";
cout << "A " << a;
cout << "\nE " << e;
cout << "\nI " << i;
cout << "\nO " << o;
cout << "\nU " << u;
cout << "\nWhitespaces - " << whitespace;
return 0;
}
I hope I just need to tweak a few things because I'm new to programming lol
I typed "WELCOME TO ARRAYS" but the vowels and whitespace shows 0
The error is here
cin >> str[99];
You must write to the beginning of the array so just pass
cin >> str;
or if you want to be more clear pass the address of the first element
cin >> &str[0];
and str will be filled from the beginning ith the chars you enter.
The >> operator only reads until the first whitespace though, so it would only count vowels of the first word.
So in general cin.getline or std::getline is better as it reads everything
cin.getline(str,sizeof(str));
Related
I've been working on this code for a while now and I keep getting the same terminal error. I have narrowed the issue down to two at functions. I've looked it up but the only answer I can seem to find is if the coder used the wrong variable in a for loop or that the variable in the at function isn't indexed properly.
Can't seem to figure out why the str.at() functions specifically are throwing errors when the variable str should be initialized. The at functions in question are the second and fourth if statements inside the do-while loop.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// start main function
int main()
{
ifstream infile;
string line;
string str;
int words = 0;
int charsNotIncludingSpaces = 0;
int charsIncludingSpaces = 0;
int wordsEndingWithE = 0;
int sixLetterWords = 0;
int wordsBeginningWithVowel = 0;
int wordsContainingATE = 0;
int allEs = 0;
int wordsWithAtleastTwoEs = 0;
infile.open("USDictionary.txt");
// read the first line from the file
getline(infile, line);
while(!infile.eof())
{
unsigned int startIndex = 0;
unsigned int endIndex = 0;
// get each word from the line and find the required results
do
{
endIndex = line.find(' ', startIndex);
if(endIndex > 0 && endIndex < line.size())
{
str = line.substr(startIndex, endIndex - startIndex);
}
else
{
str = line.substr(startIndex);
}
startIndex = endIndex + 1;
words++;
charsNotIncludingSpaces += str.size();
if(str.at(str.size() - 1) == 'e')
{
wordsEndingWithE++;
}
if(str.size() == 6)
{
sixLetterWords++;
}
if(str.at(0) == 'a' || str.at(0) == 'A'
|| str.at(0) == 'e' || str.at(0) == 'E'
|| str.at(0) == 'i' || str.at(0) == 'I'
|| str.at(0) == 'o' || str.at(0) == 'O'
|| str.at(0) == 'u' || str.at(0) == 'U')
{
wordsBeginningWithVowel++;
}
unsigned int ateIndex = str.find("ate");
if (ateIndex >= 0 && ateIndex < str.size())
{
wordsContainingATE++;
}
for (unsigned int k = 0; k < str.size(); k++)
{
if(str.at(k) == 'e')
allEs++;
}
if (str.find_first_of('e') != str.find_last_of('e'))
{
wordsWithAtleastTwoEs++;
}
} while (endIndex > 0 && endIndex < line.size());
charsIncludingSpaces += line.size();
// read the next line from the file
getline(infile, line);
}
infile.close();
/*// print the results
cout << "Total number of words in the dictionary: "
<< words << endl;
cout << "Total number of characters in the dictionary (not including white spaces): "
<< charsNotIncludingSpaces << endl;
cout << "Total number of characters in the dictionary (including white spaces): "
<< charsIncludingSpaces << endl;
cout << "Total number of words ending in the letter e: "
<< wordsEndingWithE << endl;
cout << "Total number of 6 letter words: "
<< sixLetterWords << endl;
cout << "Total number of words beginning with a vowel: "
<< wordsBeginningWithVowel << endl;
cout << "Total number of words containing the substring \"ate\": "
<< wordsContainingATE << endl;
cout << "Total number of occurances of the letter e: "
<< allEs << endl;
cout << "Total number of words containing at least two occurances of the letter e: "
<< wordsWithAtleastTwoEs << endl;*/
return 0;
}
I am trying to work out how I would be able to implement this autokey cipher and think that I have most of it worked out. The cipher is supposed to use a subkey style system using the characters positions in the alphabet.
Currently I am stuck on how to handle a few symbols " ;:,." when they are input as part of the encryption or decryption string and and not sure how to approach it as I am new to the language. Any guidance or direction would be wonderful. Posed the code and an example of how the cipher should work below.
Cipher Description:
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
//Declares
char autokeyE(int, int);
char autokeyD(char);
char numToLetter(int);
int letterToNum(char);
int main()
{
//Declares
string inputText, finalText;
int firstAlpha = 0;
int key = 0;
int option = 0;
//First Values
do
{
cout << "What operation would you like to do? Press '1' for Encrypt and '2' for Decrypt." << endl ;
cin >> option;
if (option == 1)
{
cout << "Please input your plain text to encrypt." << endl ;
cin >> inputText;
cout << "Please input your key to encrypt with." << endl;
cin >> key;
string finalText = "";
firstAlpha = letterToNum(inputText[0]);
finalText = numToLetter((firstAlpha + key) %26);
//inputText[0] = finalText[0];
for (int x = 1; x < inputText.length(); x++)
{
finalText += autokeyE(letterToNum(inputText[x-1]), letterToNum(inputText[x]));
}
cout << finalText << endl;
}
if (option == 2)
{
cout << "Please input your encrypted text to decrypt." << endl ;
cin >> inputText;
string finalText = "";
firstAlpha = letterToNum(inputText[0]);
finalText = numToLetter((firstAlpha + key) %26);
for (int x = 1; x < inputText.length(); x++)
{
//cout << inputText[x]; Testing output
finalText += autokeyD(inputText[x]);
}
cout << finalText << endl;
}
}
while (!inputText.length() == 0);
}
char autokeyE(int c, int n)
{
cout << "Keystream: " << n << " | Current Subkey: " << c << endl;
int result = 0;
//c = toupper(c);
result = ((c + n) +26 )%26;
cout << "C as a numtoletter: " << numToLetter(result) << " Result: " << result << endl;
return numToLetter(result);
return c;
}
char autokeyD(char c)
{
//Decrypting Shift -1
if (isalpha(c))
{
c = toupper(c);
c = (((c - 65) - 1) % 26) + 65;
}
return c;
}
char numToLetter(int n)
{
assert(n >= 1 && n <= 32);
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ ;:,."[n];
}
int letterToNum(char n)
{
if (isalpha(n))
{
n = toupper(n);
return(int) n - 65;
}
else
{
cout << "REUTRNING A NON ALPHA CHARACTER AS: " << n << endl;
return(int) n -30;
}
}
I don't understand your question, but I reckon the answer would be to do a back slash before each character that does not work, like so: "\;\:\,\." ( some of these may work, so only do it on the ones that don't)
You can handle symbols using isPunct in C++ such as:
if (isPunct(inputText[x]) {
//do whatever it is you need to do
}
I am working on a hangman game where incorrect letter guesses are stored in a char array called wrongletters. Of course, the user begins the game with zero wrongletters, so the wrongletters array remains empty upon declaration. The problem I am having is that when I try to display the wrong letters, the letters are spaced very far to the right because of all the other non-value elements in the array
Intended: (Guessed Letters: A B C D)
Current: (Guessed Letters: (Extra Spaces) A B C D)
Any thoughts? (I am aware game does not function properly yet):
void gameSequence() // Runs the hangman game loop
{
// Local and Global Variable Declaration and Initialization
char guessLetter = ' ';
guessWord = strToUpper(getNextWord());
string maskedWord(guessWord.size(), '_');
char wrongLetters[26] = {};
int numWrongLetters = sizeof(wrongLetters) / sizeof(wrongLetters[0]);
// Input, Process, and Output
cout << "\nLet's PLAY\n\n";
for (int i = 0; i < maskedWord.length(); i++)
cout << maskedWord[i] << " ";
while (incorrectCount < 6)
{
drawHangman(incorrectCount);
cout << "<<<<<<<<<< MAKE A GUESS >>>>>>>>>>\n\n";
cout << "Guessed Letters: ";
for (int i = 0; i < 26; i++)
cout << wrongLetters[i] << " ";
cout << "\n\nEnter a letter to guess: ";
cin >> guessLetter;
cout << endl;
guessLetter = toupper(guessLetter);
for (int i = 0; i < maskedWord.length(); i++)
cout << maskedWord[i] << " ";
if (guessWord.find(guessLetter) != string::npos)
{
for (int i = 0; i < maskedWord.length(); i++)
{
if (maskedWord[i] == guessLetter)
maskedWord[i] = guessLetter;
}
}
else
{
incorrectCount++;
wrongLetters[incorrectCount] = guessLetter;
bubbleSort(wrongLetters, numWrongLetters);
}
if (incorrectCount == 6)
{
drawHangman(incorrectCount);
cout << "Sorry you lose - the word was: " << guessWord << endl << endl;
}
}
incorrectCount = 0;
}
As I understand the array wrongletters contain at the beginning it of the wrong letters guesed so far. So there is no point of print all of it and especially sort all of it.
Hence you should change:
for (int i = 0; i < incorrectCount; i++) // incorrectCount replaced 26
cout << wrongLetters[i] << " ";
...
else
{
incorrectCount++;
wrongLetters[incorrectCount] = guessLetter;
bubbleSort(wrongLetters, incorrectCount+1); // incorrectCount replaced numWrongLetters
}
Otherwise when you sort all of the array the spaces go first before the wrong letters.
Because even if your char sequence is empty, you ask in your loop to display a space after the wrongLetters[i]. Replace the ' ' by endl and you will have
A
B
C
D
I would like to to print a triangle with a given letter. For example, if I input D, the program should return:
A
AB
ABC
ABCD
So far, I have managed to print all letters until the given one in my example, but as you see this method is not quite effective since I need to do this for all 26 cases since the English alphabet is 26 chars. Is there some way to optimize my code?
#include <iostream>
using namespace std;
int main() {
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
if (65 < c) {
cout << "A";
cout << endl;
}
if (66 < c) {
cout << "AB";
cout << endl;
}
if (67 < c) {
cout << "ABC";
cout << endl;
}
for (int i = 64; i < c; i++) {
cout << static_cast<char>(i + 1);
}
return 0;
}
You definitely need to work on your comprehension of loops. This one works just fine and it even has some checks on what is typed in and it eventually converts lower case letters into upper casse.
char first = 'A';
char last = 0;
cout << "Enter a char: ";
cin >> last;
fflush(stdin);
cout << "\n\n";
if ((last > 96) && (last < 123)) //97 to 122 are lower case letters
{
last -= 32; //32 is the delta between each lower case letter and its upper case "twin"
}
if ((last > 64) && (last < 91))
{
for (char i = 65; i <= last; i++)
{
for (char j = 65; j <= i; j++)
{
cout << j;
}
cout << "\n";
}
}
else
{
cout << "\nWrong character!!\n\n";
return 0;
}
Use a nested loop structure. Use the outer loop to 'walk' down your triangle,
lineLength = 1;
while(lineLength <= (c - 64)){
...stuff...
lineLength++;
cout << endl;
}
Use the inner loop to 'walk' down the alphabet (you've already done most of this):
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
Putting it together:
lineLength = 1;
while(lineLength <= (c - 64)){
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
lineLength++;
cout << endl;
}
I see that someone else has posted a similar answer. Between these two answers, you should be able to find your way. I haven't compiled and run this code, but I believe that it should work or be very close.
Don't harcode ascii integer values into code. Explicitly use the character or string literals (e.g. 'A' instead of 65)
Start with a helper function to print exactly one line
// prints all the characters of the alphabetic sequence from "A" to the final char designated by <c>
void printTriangleLine(char c)
{
if ((c < 'A') || (c > 'Z'))
{
return;
}
for (char x = 'A'; x <= c; x++)
{
cout << x;
}
cout << endl;
}
Then put it all together in your main:
int main()
{
char i;
cout << "Enter char ";
cin >> i;
if ((i < 'A') || (i > 'Z'))
{
return 0;
}
for (char x = 'A'; x <= i; x++)
{
printTriangleLine(x);
}
return 0;
}
We must run the loop from position is above 'A' character
until we reached the charanter you enter
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
in each loop we increment character value by 1 to go to the next value
// go to next letter
chNew++;
inner loop simply print the character from A to next value relative to current chNew + 1, it is because we also want to include current character to our printed line.
Here is your working code.
#include <iostream>
using namespace std;
int main()
{
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
// start with 'A' - 1 character
char chNew = 'A' - 1;
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
// we have done
return 0;
}
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
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAX_NUMS = 200; // Constant for the maximum number of words.
const int MAX_GUESSES = 8;
const string LETTERS = "abcdefghijklmnopqrstuvwxyz";
char inputLetter();
int findChar(char letter, string&word);
string getGuessedWord(string&secretWord, string&lettersGuessed);
string getLettersGuessed(char letter, string&lettersGuessed, int n);
void display(string&lettersGuessed, string&wordGuessed, int num, int pos);
bool isDone(string wordGuessed);
int main()
{
string oneWord; // holds one word from input file
string secretWord; // holds secret word to be guessed
string words[MAX_NUMS]; // holds list of words from input file
int randomValue; // holds index of secret word
int count = 0; // holds number of words in the file
// Declare an ifstream object named myFile and open an input file
ifstream myFile;
myFile.open("P4Words.txt");
// Exit program if cannot open file for input
if (!myFile)
{
cout << "Error: Unable to open file for input" << endl;
return 0;
}
// Input words from a file into words array
// Add your code here ...
myFile >> oneWord;
while (!myFile.eof())
{
words[count] = oneWord;
count++;
myFile >> oneWord;
}
myFile.close();
cout << count << " words loaded." << endl;
srand(static_cast<unsigned int>(time(0)));
// Select a secret word
// Add your code here ...
secretWord = words[rand() % (count + 1) ];
// Possible useful variables the loop
string lettersGuessed = ""; // holds letters guessed so far
string wordGuessed; // holds current word guessed like �_ pp_ e�
int incorrectGuesses = 0; // holds number of incorrect guesses so far
char letter; // holds a guessed letter
bool done = false; // have not guessed the word yet
int num = 8; int pos;
cout << "Welcome to the game, Hangman V1 by Your Name!" << endl;
cout << "I am thinking of a word that is " << secretWord.length()
<< " letters long." << endl;
// Set up a loop to input guesses and process
// Add your code here ...
do
{
letter = inputLetter();
pos = findChar(letter, secretWord);
wordGuessed = letter;
lettersGuessed = getLettersGuessed(letter, lettersGuessed, 8 - num);
wordGuessed = getGuessedWord(secretWord, lettersGuessed);
display(lettersGuessed, wordGuessed, num, pos);
done = isDone(wordGuessed);
num--;
} while ((num > 1) && (done == false));
// Check for won or lost
// Add your code here ...
if (done == false)
{
cout << "sorry you lose..." << endl;
}
if (done == true)
{
cout << "congratulations! " << endl;
}
system("pause"); // stop program from closing, Windows OS only
return 0;
}
// Add function definitions here ...
char inputLetter()
{
int i;
char letter;
do
{
cout << "please guess a letter: " << endl;
cin >> letter;
for (i = 0; i < 25; i++)
{
if (letter == LETTERS[i])
{
return letter;
}
}
if (letter != LETTERS[i])
{
cout << "Oops! That is an invalid character." << endl;
}
} while (letter != LETTERS[i]);
}
int findChar(char letter, string &word)
{
int i = 0; int pos = 0; bool found = false;
do
{
if (word[pos] == letter)
{
return pos;
found = true;
}
pos++;
} while (pos<word.length() - 1);
if (found == false)
{
return -1;
}
}
string getGuessedWord(string&secretWord, string&letterGuessed)
{
string temp;
temp = secretWord;
for (size_t k = 0; k <= temp.length() - 1; k++)
{
temp[k] = '_';
}
for (size_t i = 0; i <= temp.length() - 1; i++)
{
for (size_t j = 0; j <= temp.length() - 1; j++)
{
if (letterGuessed[i] == secretWord[j])
{
temp[j] = letterGuessed[i];
}
}
}
return temp;
}
string getLettersGuessed(char letter, string&lettersGuessed, int n)
{
string temp;
temp = letter;
lettersGuessed.insert(n, temp);
return lettersGuessed;
}
void display(string&lettersGuessed, string&wordGuessed, int num, int pos)
{
if (pos != -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Good guess!: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
if (pos == -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Oops! that letter is not my word: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
}
bool isDone(string wordGuessed)
{
bool done = false; int k = 0;
for (size_t i = 0; i <= wordGuessed.length() - 1; i++)
{
if (wordGuessed[i] == '_')
{
k++;
}
}
if (k == 0)
{
done = true;
}
return done;
}
it says subscript is out of range I need help to fix it
let me know how to fix it please its a project that is due very soon
that's all I got so far
Change:
for (size_t i = 0; i <= temp.length() - 1; i++)
to:
for (size_t i = 0; i <= letterGuessed.length() - 1; i++)