Element counting issue [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int countLetters(char text[], char letter);
int main()
{
char letter;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
char text[1024];
cout << "Enter text: ";
cin.getline(text, 1024);
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(char text[], char letter)
{
int letterCount = 0;
for (int i = 0; i <= text[i]; i++)
{
if (letter == text[i])
letterCount++;
}
return letterCount;
}
This code, as written, is designed to ask the user for, first, the letter they want to search for in a line of text. Second, it will ask the user to input the line of text they want to have searched. Finally, it will spit out how many letters there are in the specific line of text they input.
My specific error lies here: when user asks for 'e' in "CS 124 - Introduction to Software Development", program only declares that there is one 'e' . I'm unsure what's wrong, because when you run the program and input 'o' while asking to search the exact same line of text, you get the proper number of 'o' values returned, 4.
Any ideas as to what my error is and why it glitches when searching for 'e' ?

Your for condition is wrong, the for loop should continue while i is less than text's length not the value of text[i]. Since this is C++ you should use strings not character arrays, why make it harder on yourself?
The code below is a C++ approach, note that my C++ is a bit rusty and the code might contain errors.
#include <iostream>
#include <string>
using namespace std;
int countLetters(string text, char letter);
int main() {
char letter = ' ';
string text;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
cout << "Enter text: ";
getline(cin, text); // use 'getline(cin, text)' instead of 'cin >> text'
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(string text, char letter) {
int letterCount = 0;
for (int i = 0; i < text.size(); i++) {
if (letter == text[i]) {
letterCount += 1;
}
}
return letterCount;
}

change the condction
i <= text[i]
to
text[i] != '\0'

Related

How can I replace every alphabetical lower case letter in a string with its opposite alphabetical lower case letter in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I would like to find the opposite letter using for loop. Also, I would like to note that I am trying to find the opposite letter. For example, replacing "a" with "z", "b" with "y"...
For example, the user inputs this: "3 feg", and the output from this program will be: "uvt". Also, my constraint is 1<=n<=100. The input format is "n input_string_of_length_n", and the output format is "encrypted_string_of_length_n". As a new beginner to programming, I am lost and I do not know how to solve this. Any help will be very much appreciated.
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
`int` user_input_number;
string user_input_text;
cout << "Type: ";
cin >> user_input_number;
cout << "Type: ";
cin >> user_input_text;
for(char i = 'a'; i <= 'z'; i++)
{
cout << << endl;
}
return 0;
}
Here is one solution using ASCII arithmetic:
string s = "abc";
for(int i = 0; i < s.length(); i++){
s[i] = 219 - s[i];
}
cout << s; // "zyx"
The reason it works is that all ASCII characters are between 0 and 127, and this way the values loop back around
// Example program
#include <iostream>
#include <string>
#include <map>
using namespace std;
string encrypt(int n, string s) {
map<char, int> alphabetMap = { };
string alpha = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 26; i++){
alphabetMap.insert({alpha[i],i});
}
string coded = "";
for (int i = 0; i < n; i++) {
int index = alphabetMap[s[i]];
coded += alpha[25 - index];
}
return coded;
}
int main()
{
int n = 0;
string s = "";
cout << "Enter n and string: " ;
cin >> n >> s;
cout << encrypt(n,s) << endl;
}

How do I loop through a string and convert to lowercase?

I know there were a couple of other questions on this from a while back, but I looked over those and still couldn't figure it out. I'm trying to take user input in the form of a string, then loop through that string converting all of the uppercase to lowercase so that I can display it all in lowercase.
Where am I going wrong?
int main()
{
cout << "Enter Text: ";
string Text;
getline(cin, Text);
for(int i=0; i<Text.length(); i++)
{
if(islower(Text[i]) == false)
{
tolower(Text[i]);
i++;
}
Text[i] = Text[i];
}
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
I'm very new to C++ and I'd be lying if I said I had much of an idea even where I was going wrong. Line 11, where the for loop is says that it's trying to compare two different signs, but I don't know what that means or if that's the source of my problem. Line 15 where the tolower() is says that it's 'ignoring return value of function declared with pure attribute' but I still don't know what that means either.
Please help.
A few points:
tolower returns the lowercase character if it exists ('A' becomes
'a', 'a' is unchanged, '9' is unchanged, etc.)
The line Text[i] = Text[i]; does not do anything, you want Text[i]
= tolower(Text[i]);
There is no need to check if each character is lowercase, tolower
will handle that for you
Simplified:
#include <iostream>
using namespace std;
int main() {
cout << "Enter Text: ";
string Text;
getline(cin, Text);
for (int i = 0; i < Text.length(); i++)
Text[i] = tolower(Text[i]);
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
I'd suggest using the std library algorithm function transform to simplify and to make the code easier to read for you and others.
#include <iostream> //for cout and getline
#include <algorithm> //for transform
int main()
{
cout << "Enter Text: ";
string Text;
getline(cin, Text);
//This will iterate over each character [Text.begin()-Text.end()] and then
//replace it by a call to tolower with itself as a parameter
transform(Text.begin(), Text.end(), Text.begin(), ::tolower);
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
EDIT:
As Remy pointed out to correct way of implenting this is by using a proxy lambda since
the behavior of std::tolower is undefined if the argument's value is
neither representable as unsigned char nor equal to EOF.
transform(Text.begin(), Text.end(), Text.begin(),
[](unsigned char c){ return std::tolower(c); });
I'd recommend looking at the ascii tables to see the codes for upper case and lower case characters.
http://www.asciitable.com/
bool islower(char in)
{
return !(char >= 'A' && char <= 'Z'); //we do this so if its a not an alphabet character we don't get false positives
}
char tolower(char in)
{
return char-'A' + 'a'; //essentially get its distance from the start of the
//alphabet and add this distance to the lowercase (only works on uppercase)
}
Its all just about working with the ascii values to get what you want since all characters are essentially integers.

Preventing user from inputting certain chars in c++ [closed]

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
I'm quite new to c++ so please understand that my question may be silly.
I need to create a function which takes from the user a table and fills it with only specific characters. Let's say that the user needs to input his name. If the user inputs a charater from A to Z (or a to z) the character should be displayed on the screen and in that case- everything is fine. The problem is- when the user inputs a forbidden character (for instance 1-9) this shouldn't be displayed on the screen and the cursor should stay in the same position).
Do you guys know how to do this?
May be you can use this to do your job:
char ch;
while(ch = getch())
{
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
cout << ch;
}
}
This will print only [A-Z][a-z]. You can also store your required char to use further.
On Windows you can use conio.h.
Also, you can overload the istream::operator>> function to make solution more elegant and easy to use:
Complete example:
#include <iostream>
#include <conio.h>
using namespace std;
struct person_t
{
string name;
string last_name;
};
// This is the function you're looking for.
void get_filtered_string(string &str)
{
char c;
str = "";
do
{
c = _getch();
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
{
putchar(c); // 1
str.push_back(c);
}
} while (c != '\r'); // 2
}
istream &operator>>(istream &stream, person_t &person)
{
string str = "";
cout << "Enter name: ";
get_filtered_string(str);
person.name = str;
cout << endl;
cout << "Enter last name: ";
get_filtered_string(str);
person.last_name = str;
cout << endl;
return stream;
}
int main()
{
person_t person;
cin >> person;
cout << person.name.c_str() << " " << person.last_name.c_str() << endl;
return 0;
}
Output character to screen.
In Windows when you hit Enter you're introducing two characters '\r' and '\n' in that order. Thats why we check here for '\r'.

Error with rand function C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a hangman program, but I'm having issues with randomly choosing a word out of the list...
I get the errors:
-error C2661: 'rand' : no overloaded function takes 1 arguments
-IntelliSense: too many arguments in function call
They are both referring to the rand function noted in the code where I'm trying to randomly choose a word out of the array so the user can guess.
// Hang.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
using namespace std;
const int MAXLENGTH=80;
const int MAX_TRIES=5;
const int MAXROW=7;
int letterFill (char, char[], char[]);
void initUnknown (char[], char[]);
int main ()
{
char unknown [MAXLENGTH];
char letter;
int num_of_wrong_guesses=0;
char word[MAXLENGTH];
char words[][MAXLENGTH] =
{
"india",
"america",
"germany",
"china",
"canada"
};
//THIS IS WHERE THE ISSUE IS OCCURRING vvvvvvv
//choose and copy a word from array of words randomly
rand();
int n=rand(5);
strcpy(word,words[n]);
// Initialize the secret word with the * character.
initUnknown(word, unknown);
// welcome the user
cout << "\n\nWelcome to Hangman!";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
// Loop until the guesses are used up
while (num_of_wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
// Fill secret word with letter if the guess is correct,
// otherwise increment the number of wrong guesses.
if (letterFill(letter, word, unknown)==0)
{
cout << endl << "Sorry, that letter was wrong." << endl;
num_of_wrong_guesses++;
}
else
{
cout << endl << "You found a letter!" << endl;
}
// Tell user how many guesses has left.
cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
cout << " guesses left." << endl;
// Check if they guessed the word.
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You guessed it!";
break;
}
}
if(num_of_wrong_guesses == MAX_TRIES)
{
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
getch();
return 0;
}
/* Take a one character guess and the secret word, and fill in the
unfinished guessword. Returns number of characters matched.
Also, returns zero if the character is already guessed. */
int letterFill (char guess, char secretword[], char guessword[])
{
int i;
int matches=0;
for (i = 0; secretword[i]!='\0'; i++)
{
// Did we already match this letter in a previous guess?
if (guess == guessword[i])
return 0;
// Is the guess in the secret word?
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
// Initialize the unknown word
void initUnknown (char word[], char unknown[])
{
int i;
int length = strlen(word);
for (i = 0; i < length; i++)
unknown[i]='*';
unknown[i]='\0';
}
// end
rand takes no argument
You probably want :
int n=rand() % 5;
std::rand() generates a pseudo random number, if you want a number 0, 1, 2 3 or 4, which i guess you are trying to do use the following:
int n = rand()%5;
This generates a random number and then the % gives the rest value if you would divide by 5. If the random number is 12, you can 'put two fives in it', and the rest value will be 2.
One thing to note is that in C++ using rand() is generally a bad idea, because it will not give you a truly random number, and using % makes it worse, but I think you will be fine since this is just a small program.
Watch this talk if you want to know how to properly generate a random number in c++

Reverse each character in a string except special characters (e.g. "?") [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
For example : how are you? ----> woh era uoy?
This is my code, i got it worked but the question mark is besing reversed too.
How can i make it remained intact?
#include <iostream>
using namespace std;
int main()
{
string ch;
while(cin >> ch)
{
for(int i = ch.length() - 1; i >= 0; i--)
{
cout << ch[i];
}
cout << " ";
}
return 0;
}
Your chosen input method (cin >> ch) automatically splits the input into separate words.
Like Jerry Coffin said in his answer, you have to skip over punctuation etc to find to alpha characters to swap. Roughly like this:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string ch;
while (cout << "String? " && cin >> ch)
{
cout << "Input: <<" << ch << ">>\n";
const char *bp = ch.c_str();
const char *ep = ch.c_str() + ch.length() - 1;
const char *sp = ch.c_str();
while (sp < ep)
{
while (sp < ep && (*sp != ' ' && !isalpha(*sp)))
sp++;
while (sp < ep && (*ep != ' ' && !isalpha(*ep)))
ep--;
char c = *sp;
ch[sp-bp] = *ep;
ch[ep-bp] = c;
sp++;
ep--;
}
cout << "Output: <<" << ch << ">>\n";
}
cout << endl;
return 0;
}
Sample dialogue
String? How are you?
Input: <<How>>
Output: <<woH>>
String? Input: <<are>>
Output: <<era>>
String? Input: <<you?>>
Output: <<uoy?>>
String? Pug!natious=punctuation.
Input: <<Pug!natious=punctuation.>>
Output: <<noi!tautcnu=psuoitanguP.>>
String?
You can tweak it from here. I'm far from claiming this is idiomatic C++; the use of const char * in the middle shows my C background.
Start from the beginning of the string, and scan forward until you find a letter. The scan backwards from the end until you find a letter. Swap them. Continue until the two positions meet.
Note: above I've used "letter", but all I really mean is "one of the characters that should be reversed." You haven't defined very precisely which characters should be swapped and which shouldn't, but I'm assuming you (or your teacher) has a reasonably specific definition in mind.
Try using array and scanning each letter to see if there is a question mark. If there is, move it to the last place of the array.
simple solution or hack to solve this case alone. if there are more cases comment it lets solve it together.
#include <iostream>
using namespace std;
int main()
{
string ch;
while(cin >> ch)
{
int flag = 0;
for(int i = ch.length() - 1; i >= 0; i--)
{
if(ch[i] != '?')
cout << ch[i];
else
flag = 1;
}
if(flag)
cout << "?";
else
cout << " ";
}
return 0;
}