string and char variable was not declared in this scope C++ - c++

I want to create a program which is able to count the characters in a word.
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
do
{
string inputWord = "";
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
do
{
char searchCh = '0';
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
}while(searchCh.size()<1 && searchCH.size()>1);
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
char ch = word.at(i);
// if the character matches the character we're looking for
if(searcCh==ch)
// increment counter
{
counter++; // counter = counter + 1
}
}
// output the number of times character appears
cout << "the word " << word << " contain character " << searchCh << "is" << counter;
return 0;
}
and I always get the error: inputWord was not declared.
What is the cause this error?

You should read about scopes. Variables in c++ have visibility and lifetime in scope, in which the were declared. For instance, inputWord is visible and exists only in the first do-while loop. Move its declaration above loop. Your code has many such errors. Moreover, I do not see, where is counter declared and it should be properly initialized.

You have mixed up a lot of variable names and used variables outside their scope.
Here is a working version of your code with a few debugs:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
string inputWord = "";
char searchCh = '0';
char ch;
int counter=0;
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
ch = inputWord[i];
// if the character matches the character we're looking for
if(searchCh==ch)
// increment counter
counter++; // counter = counter + 1
}
// output the number of times character appears
cout << "the word " << inputWord << " contain character " << searchCh << " is " << counter;
return 0;
}

You declared the inputWord as string, please check your compiler works for that or not because some compilers do not take the specifier "string". Also searchCh, counter and word is also missing from your program. First of all declare these variables properly.

you should define the "inputWord" before start the while loop , like this :
string inputWord = "";
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
because "inputWord" is inside the loop ,

Related

Checking greater character

Giving 5 inputs, program will check which entered character is the greater (assume characters are alphabets here only).
This is the code I've written (All variables are of char data type).
Problem is, it's printing the last entered character every time which makes it obvious the logic is faulty..
Here's the code I've written:
cout << "Enter a character ";
cin >> chr;
for (int i = 0; i < 4; i++)
{
cout << "Enter a character ";
cin >> chr2;
if (chr > chr2)
{
store = chr;
}
else
{
store = chr2;
}
chr = chr2;
}
cout << "Greater character is "<< store << endl;
You are making your code far too complex! What you need to do is first set your 'rolling' maximum (the store variable) to a value lower than any possible input (let's say 0) then run a single loop to read in each of the test characters. On each input, compare the given character to your 'rolling' max and, if it's greater, set that rolling max to the given input.
Something like this:
char store = 0, chr;
for (int i = 0; i < 5; ++i) {
cout << "Enter a character ";
cin >> chr;
if (chr > store) store = chr;
}
cout << "Greatest character is "<< store << endl;
Feel free to ask for further clarification and/or explanation.
The problem here is that you are always comparing with the previous character, not the biggest-seen character.
In my opinion, the control flow can be simplified. Try something like this:
/* Rather than pull the first iteration out of the loop, begin with the minimum value */
char greatest = std::numeric_limits<char>::min();
for(int i = 0; i < 5; i++)
{
std::cout << "Enter a character: " << std::endl;
char input;
std::cin >> input;
/* We only need to replace `greatest` with `input` if `input` is greater */
if(input > greatest)
{
greatest = input;
}
}
std::cout << "Greatest character is: " << greatest << std::endl;
Your code chr = chr2; in the last before line tells the code to store the last entered value in the chr and this means you are comparing only the last and last before entered value in the program,
To change the program to suit your need , Change chr = store; which tells the program to store the greatest char entered to be stored inside char variable .
cin >> chr;
for (int i = 0; i < 4; i++)
{
cout << "Enter a character ";
cin >> chr2;
if (chr > chr2)
{
store = chr;
}
else
{
store = chr2;
}
chr = store;
}
cout << "Greater character is "<< store << endl; ````
Hope this helps!!

checking for character pair in array

I have a character array that produces a random array of lowercase letters in the length that the user inputs. my problem is that after the array of random letters is produced the user inputs a pair of charaters(two letters) and my code should check if that pair is in the random array that was produced. it worked fine when it just checked for one letter but when i introduced the second one it does not work.I would appreciate any help.
#include <ctime>
#include <iostream>
#include <cstdlib>
int main() {
std::srand(std::time(NULL));
int i, num;
char letter1, letter2, ch, r;
const char chars[]="abcdefghijklmnopqrstuvwxyz";
std::cout << "How many letters do you want in your string? ";
std::cin >> num;
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
std::cout << "\nWhat letter pair would you like to find? ";
std::cin >> letter1 >> letter2;
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
}
First, you are not storing your randomly generated chars
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
This just writes a random char in ch and displays it on the console with each iteration. You don't store your data, ch just contains the last random char after your loop ends and everything else is lost.
The part where you want to search is double wrong.
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
This isn't inside a loop, i is simply always going to be num-1.
The array you are checking is chars which is your const array containing "abcdefghijklmnopqrstuvwxyz". This doesn't contain your randomly generated chars.

How to check if char doesnt exist in a string

Say we have the user input a name that is a string "william" and then the user enters the character that they want to find the index of.
using namespace std;
string name;
char characterToFind;
cout << "Enter a name ";
cin >> name;
cout << "Enter a character to find ";
cin >> characterToFind;
We then want to find the index of the character in the name string array.
for (int j = 0; j < name.length(); j++) {
if (name[j] == characterToFind) {
cout << "char is at index: " << j << endl;
}
}
How do I then check if the inputted character doesnt exist in the name string array? I try to do the following:
if (characterToFind != name.find(characterToFind)) {
cout<< "doesnt exist" << endl;
}
The if statement always seems to be true and runs the code even if the character that was inputted existed in the name string array.
The problem with my approach was that I was doing was that in the if condition i was checking a 's' char vs a index position of an array.
instead, doing:
if (name.find(characterToFind) == std::string::npos) {
cout << "doesnt exist" << endl;
}
this is checking if the character input is equal to a position that doesnt exist! This is true so it tells the user that the character entered does not exist.

My c++ program doesn't complete and closes

This program counts the number of times a specific character appears in a string. The compiler shows me an incomplete output without displaying how many times the character shows in the input then closes abruptly
Enter a string (up to 50 characters): k;kl;kl;k;kljhh
Enter a character and I will tell you how many
times it appears in the string: k
k appears Press any key to continue...
I'm using VS community.
// This program demonstrates a function, countChars, that counts
// the number of times a specific character appears in a string.
#include <iostream>
using namespace std;
int countChars(char *, char); // Function prototype
int main()
{
const int SIZE = 51; // Array size
char userString[SIZE]; // To hold a string
char letter; // The character to count
// Get a string from the user.
cout << "Enter a string (up to 50 characters): ";
cin.getline(userString, SIZE);
// Get a character to count occurrences of within the string.
cout << "Enter a character and I will tell you how many\n";
cout << "times it appears in the string: ";
cin >> letter;
// Display the number of times the character appears.
cout << letter << " appears ";
cout << countChars(userString, letter) << " times.\n";
return 0;
}
//****************************************************************
// Definition of countChars. The parameter strPtr is a pointer *
// that points to a string. The parameter Ch is a character that *
// the function searches for in the string. The function returns *
// the number of times the character appears in the string. *
//****************************************************************
int countChars(char *strPtr, char ch)
{
int times = 0; // Number of times ch appears in the string
// Step through the string counting occurrences of ch.
while (*strPtr != '\0')
{
if (*strPtr == ch) // If the current character equals ch...
times++; // ... increment the counter
strPtr++; // Go to the next char in the string.
}
return times;
}
Unable to reproduce on Ubuntu. Perhaps a windows issue?
#include <iostream>
#include <iomanip>
class T590_t
{
std::stringstream ssin;
public:
T590_t() = default;
~T590_t() = default;
int exec(int , char** )
{
ssin << "k;kl;kl;k;kljhh\nk"; // for consistent behavior, use stringstream for input
// the letter ------------^
const int SIZE = 51; // Array size
char userString[SIZE]; // To hold a string
// Get a string from the user.
std::cout << "\n Enter a string (up to 50 characters): ";
(void)ssin.getline(userString, SIZE);
std::cout << "\n '" << userString << "'" << std::endl; // echo input
// Get a character to count occurrences of within the string.
std::cout << "\n Enter a character and I will tell you how many times it appears in the string: ";
char letter = '\0'; // The character to count, initialized
ssin >> letter;
std::cout << " '" << letter << "'" << std::endl; // echo input
// Display the number of times the character appears.
std::cout << "\n " << letter << " appears "
<< countChars(userString, letter) << " times.\n";
return 0;
}
private: // methods
int countChars(char *strPtr, char ch)
{
int times = 0; // Number of times ch appears in the string
// Step through the string counting occurrences of ch.
while (*strPtr != '\0')
{
if (*strPtr == ch) // If the current character equals ch...
times++; // ... increment the counter
strPtr++; // Go to the next char in the string.
}
return times;
}
}; // class T590_t
int main(int argc, char* argv[])
{
T590_t t590;
return t590.exec(argc, argv);
}
with output:
Enter a string (up to 50 characters):
'k;kl;kl;k;kljhh'
Enter a character and I will tell you how many times it appears in the string: 'k'
k appears 5 times.
You can pass an array of characters and its size instead:
int GetCharCount(char[], const int, const char);
int main(){
char text[] = "Hello there!";
cout << GetCharCount(text, strlen(text), 'e') << endl;
cout << endl << endl;
cin.get();
return 0;
}
int GetCharCount(char pTxt[], const int size, const char c){
int count = 0;
for(int i(0); i != size; i++)
if(c == pTxt[i])
count++;
return count;
}

Finding non-whitespace characters in C++

For my assignment, I have to call a function that takes the user input and spits out the number of non-whitespace characters. Inside the program, I have this code:
int GetNumOfNonWSCharacters(const string givenText) {
int counter;
for (int i = 0; i < givenText.length(); i++) {
if (givenText.at(i) != ' ') {
counter++;
}
}
return counter;
}
When I return the counter integer, this is how I output it with the string sampleText being the input:
if (menuInput == 'c' || menuInput == 'C') {
cout << "Number of whitespaces: " << GetNumOfNonWSCharacters(sampleText) << endl;
}
It returns an answer like 1231341235 or something along those lines. Now, when I type this code into a different file, pretty sure it's identical, I get the correct result every time:
int NumNonWhitespaces(const string userInput) {
int counter;
for (int i = 0; i < userInput.length(); i++) {
if (userInput.at(i) != ' ') {
counter++;
}
}
return counter;
}
int main() {
string userString;
cout << "Enter some text" << endl;
getline(cin, userString);
cout << "You entered: " << userString << endl;
cout << NumNonWhitespaces(userString);
return 0;
}
Does anyone have a solution to the problem ?
There is even more simple way to count the number of non white spaces by using the STL count algorithm:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string userString;
cout << "Enter some text" << endl;
getline(cin, userString);
cout << "You entered: " << userString << endl;
//count the number of white spaces
int numberOfWhiteSpace = count(userString.begin(), userString.end(), ' ');
//substruct that number from the total length of your string
cout << "number of non-whitespace: " << userString.length() - numberOfWhiteSpace;
return 0;
}
But in your solution you have to initialize the variable counter to 0
If you use counter without initializing it first, you'll get whatever junk memory existed at its memory address before your program started using it (C++ does not automatically zero-out the memory when you declare a variable). The fact it works when you copy it into a new file is purely coincidental.
The fix is simply to initialize counter to 0 before using it:
int counter = 0;
In some programming languages if a variable is allocated but not assigned, it is said to have a "garbage value" , that is, some information that was being held any random piece of the computer's memory. So initialize the counter variable to 0
You have to initialise the counter variable otherwise it will contain any old value.
int counter=0;