looping through a character array c++ [closed] - c++

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 6 years ago.
Improve this question
#include <iostream>
#include <string>
using namespace std;
bool custNum(char [], int);
int main()
{
const int size = 8;
char custmor[size];
cout << "Enter a customer number in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN = numbers): ";
cin.getline(custmor, size);
if(custNum(custmor, size))
cout<<"That's a valid id number"<<endl;
else
cout<<"That's not a valid id number"<<endl;
return 0;
}
bool custNum(char custNum[], int size)
{
int count;
for(count = 0; count<3; count++)
{
if(!isalpha(custNum[count]))
return false;
}
for(count = 3; count <size - 1; count++) //3<7 , 4
{
if(!isdigit(custNum[count]))
return false;
}
return true;
}
so I want to loop through a character array of 3 letters and 4 numbers like ABC1234, but I didn't get the condition of the second for loop (size - 1). How does it work every time it tests the condition?

Never use count as a loop variable. A good name for a loop variable is i.
Never declare variables away from their initialization. The above should be for( int i = 0; ... in both cases.
i < size - 1 is probably wrong. What you probably want is i < size.
Anyhow, it would help if you showed how size is declared, how it is initialized, etc. It would also help if you showed the exact text you are trying to parse. It would also help if you explained exactly what you expected to happen, and exactly what happened instead. I might amend my answer when you do that.

you read only amount of characters that size variable specify,
since then , Why custNum function would not return true for anything longer than size variable ? , Because it's not checking anything more than what size variable specify.
Below is the code you need
#include <iostream>
#include <string>
using namespace std;
bool custNum(string,unsigned int);
int main()
{
const unsigned int size = 8;
//char custmor[size];
string mystring;
cout << "Enter a customer number in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN = numbers): ";
cin >> mystring;
cout << mystring <<endl << " " << mystring.length() << endl;
// cin.getline(custmor, size);
if(custNum(mystring , size))
cout<<"That's a valid id number"<<endl;
else
cout<<"That's not a valid id number"<<endl;
return 0;
}
bool custNum(string s, unsigned int size)
{
unsigned int count;
if (s.length() != (size + 1))
return false;
for(count = 0; count<3; count++)
{
if(!isalpha(s[count]))
return false;
}
for(count = 3; count <size - 1; count++) //3<7 , 4
{
cout << s[count] <<endl;
if(!isdigit(s[count]))
return false;
}
return true;
}

Related

C++ Can't retrieve private variable from class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am writing a program that generates integers and sets the range of the user's choosing.
For example:
Enter the number of integers: 4
Range: 10
4 9 2 1 are generated
Now the user chooses 4 digits at a time until they're correct.
Program will also tell user if they are partially correct.
For example:
User input: 4 9 0 7
Console << 2 of your answers are correct.
I have three files:
Driver.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main()
{
// Declare variables.
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) {
cout << "Enter the Number of Integers (n): " << endl;
cin >> numberOfIntegers;
cout << "Number of Each Integers from 1 to (m): " << endl;
cin >> rangeOfIntegers;
cout << "Enter your guesses for the " << numberOfIntegers << " integers in the range from 1 to " << rangeOfIntegers << " that have been selected:" << endl;
guess.beginGuessingGame(rangeOfIntegers, numberOfIntegers);
}
if (count == numberOfIntegers) {
cout << "You are correct! Play again? (y/n)";
}
else {
cout << count << " of your guesses are correct." << endl;
}
};
Game.h
// identifiers
#ifndef guessing_game
#define guessing_game
class Guess
{
private :
int * generatedSequence;
int * inputGuess;
int sum;
public :
void generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers);
void beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers);
int getSum() {
return sum;
}
};
#endif
and Game.cpp
#include <iostream>
#include <iomanip>
#include "Game.h"
using namespace std;
void Guess::generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Initialize random number generator.
srand(time(0));
/// Declare array size for the generated sequence to be based on user input.
generatedSequence = new int[inputRangeOfIntegers];
/// Input randomly generated numbers from from 0 to input range into generatedSequence.
for (int i = 0; i < inputNumberOfIntegers; i++) {
generatedSequence[i] = rand() % inputRangeOfIntegers + 1;
cout << generatedSequence[i] << " " << endl;
}
}
void Guess::beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Call our generateSequence function.
generateSequence(inputRangeOfIntegers, inputNumberOfIntegers);
/// Declare guess size based on user input.
inputGuess = new int[inputNumberOfIntegers];
/// Begin endless loop for user to guess integers.
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
}
My issue is: I cant retrieve that sum variable in the main class to check it against the number of integers. Because if they are equal, then the program knows the user has guessed correctly. I cant use cout after calling the beginGuessingGame function either..
Any suggestions?
Thanks.
At least this part of the program
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) { //...
does not make sense. The program has undefined behavior.
Data members of the class object guess are not initialized So the member function getSum returns an indeterminate value of the data member sum of the object. And this indeterminate value is compared with another indeterminate value of the uninitialized variable numberOfIntegers in the while loop.
In the function generateSequence it seems there is a typo in this statement
generatedSequence = new int[inputRangeOfIntegers];
There should be
generatedSequence = new int[inputNumberOfIntegers];
Within the function beginGuessingGame there is an infinite loop
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}

A program to find out if a word is palindrome

Written some algorithm to find out if a given word is a palindrome. But one of my variables (counter) seems not updating when I debugged and I can't figure out what is wrong with it. I may be wrong though... any help will be needed as I don's wanna copy some code online blindly.
Below is the code:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
//take input
string input;
cout << "Enter your word: ";
cin >> input;
//initialize arrays and variables
int counter = 0, k = 0;
int char_length = input.length();
char characters[char_length];
strcpy(characters, input.c_str());//copy the string into char array
//index of character at the midpoint of the character array
int middle = (char_length-1)/2;
int booleans[middle]; //to keep 1's and 0's
//check the characters
int m = 0, n = char_length-1;
while(m < middle && n > middle){
if(characters[m] == characters[n]){
booleans[k] = 1;
} else {
booleans[k] = 0;
}
k++;
m++;
n--;
}
//count number of 1's (true for being equal) in the booleans array
for(int i = 0; i < sizeof(booleans)/sizeof(booleans[0])-1; i++){
counter += booleans[i];
}
//compare 1's with size of array
if(counter == middle){
cout << input << " is a Palindrome!" << endl;
} else {
cout << input << " is not a Palindrome!" << endl;
}
return 0;
}
Brother it seems difficult to understand what your question is and what code you are typing. I am not very much experienced but according to me palindrome is a very very simple and easy program and i would have wrote it as:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str1[20], str2[20];
int i, j, len = 0, flag = 0;
cout << "Enter the string : ";
gets(str1);
len = strlen(str1) - 1;
for (i = len, j = 0; i >= 0 ; i--, j++)
str2[j] = str1[i];
if (strcmp(str1, str2))
flag = 1;
if (flag == 1)
cout << str1 << " is not a palindrome";
else
cout << str1 << " is a palindrome";
return 0;
}
It will work in every case you can try.
If you get a mismatch i.e. (characters[m] == characters[n]) is false then you do not have a palindrome. You can break the loop at that point, returning false as your result. You do not do that, instead you carry on testing when the result is already known. I would do something like:
// Check the characters.
int lo = 0;
int hi = char_length - 1;
int result = true; // Prefer "true" to 1 for better readability.
while (lo < hi) { // Loop terminates when lo and hi meet or cross.
if(characters[lo] != characters[hi]) {
// Mismatched characters so not a palindrome.
result = false;
break;
}
lo++;
hi--;
}
I have made a few stylistic improvements as well as cleaning up the logic. You were doing too much work to solve the problem.
As an aside, you do not need to check when the two pointers lo and hi are equal, because then they are both pointing to the middle character of a word with an odd number of letters. Since that character must be equal to itself there is not need to test. Hence the < in the loop condition rather than <=.
Existing Code does not work for Palindromes of Odd Length because of
for(int i = 0; i < sizeof(booleans)/sizeof(booleans[0])-1; i++)
Either use i<=sizeof(booleans)/sizeof(booleans[0])-1; or i<sizeof(booleans)/sizeof(booleans[0]);.
Currently, you are not counting the comparison of character[middle-1] and character[middle+1].
For palindromes of even length, you will have to change your logic a bit because even length palindromes don't have a defined middle point.
#include <iostream>
#include <cstring>
using namespace std;
int main(){
//take input
string input;
cout << "Enter your word: ";
cin >> input;
//initialize arrays and variables
int counter = 0, k = 0;
int char_length = input.length();
char characters[char_length];
strcpy(characters, input.c_str());//copy the string into char array
//index of character at the midpoint of the character array
int middle = (char_length+1)/2;
int booleans[middle]; //to keep 1's and 0's
//check the characters
int m = 0, n = char_length-1;
while(m<=n){
if(characters[m] == characters[n]){
booleans[k] = 1;
} else {
booleans[k] = 0;
}
k++;
m++;
n--;
}
//count number of 1's (true for being equal) in the booleans array
for(int i = 0; i < sizeof(booleans)/sizeof(booleans[0]); i++){
counter += booleans[i];
}
cout<<counter<<" "<<middle<<endl;
//compare 1's with size of array
if(counter == middle){
cout << input << " is a Palindrome!" << endl;
} else {
cout << input << " is not a Palindrome!" << endl;
}
return 0;
}
Over here the size of the boolean array is (length+1)/2,
For string s like abcba it will be of length 3.
This corresponds to a comparison between a a, b b and c c. Since the middle element is the same, the condition is always true for that case.
Moreover, the concept of middle is removed and the pointers are asked to move until they cross each other.

Searching for the frequency of a word in a string (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 2 years ago.
Improve this question
I have to write a program that asks the user for a sentence (with a limit of 1024 letters), then asks the user for a word, and tells the user how many times that specific word occurs in the sentence, for an assignment.
We're only allowed to use these libraries: iostream, string, cstring, cstdlib, cmath and fstream.
example of how it's supposed to function:
Enter a sentence:
input:hello my name is hello hello
Enter a word to check for frequency:
input:hello
desired output:# of times word occurs: 3
actual output:# of times word occurs: 25
This is what I tried using with the help of a friend, but when I enter a word to search it outputs an unrelated number.
int wordFrequency(){
char sen5[1024];
int frequency = 0;
char word[1024];
cout << "Enter a sentence: " << endl;
cin.getline(sen5, 1024);
cout << "Enter a word to check for frequency: " << endl;
cin.getline(word, 1024);
for(int i = 0; i < strlen(sen5); i++){
if(sen5[i] == word[i]){
for(int j = 0; j < strlen(word); j++)
if(sen5[j] == word[j])
frequency += 1;
}
}
cout << "# of times word occurs: " << frequency << endl;
return 0;
}
Also, I'm aware my coding is horrid, my professor is notoriously horrible and I'm struggling immensely in my class because of it. Any help is appreciated.
So friend if you are only allowed to use isostream,, string, cstring, cstdlib, cmath and fstream. then you can program it in C++ language.
So below code only uses iostream for input/output operations.
you can also use string.h to find the string length but i have gone the other way.
for finding the occurrence's of a word below is the function:
int countOccurrences(char * str, char * toSearch)
{
int i, j, found, count;
int stringLen, searchLen;
int cou = 0;
while(str[cou] != '\0'){
cou++;
}
stringLen = cou;
cou = 0;
while(toSearch[cou] != '\0'){
cou++;
}
searchLen = cou;
count = 0;
for(i=0; i <= stringLen-searchLen; i++)
{
found = 1;
for(j=0; j<searchLen; j++)
{
if(str[i + j] != toSearch[j])
{
found = 0;
break;
}
}
if(found == 1)
{
count++;
}
}
return count;
}
And for taking the input you can write the things in main function and then call the above function in main. Below is the code for that:
int main()
{
char str[MAX_SIZE];
char toSearch[MAX_SIZE];
int count;
cout<<"Enter any string: "<<endl;
cin.getline(str, sizeof(str));
cout<<"Enter word to search occurrences: "<<endl;
cin.getline(toSearch, sizeof(toSearch));
count = countOccurrences(str, toSearch);
cout<<"Total occurrences of"<< toSearch<<" : "<< count;
return 0;
}
It seems you are beginner in the coding stuff so for more:
below is the code you need to add at the starting of your code. Header file and declaring the countOccurences function.
#include <iostream>
#define MAX_SIZE 100
using namespace std;
int countOccurrences(char * str, char * toSearch);
So this way you can count the number of occurrences/frequency of a word in a string with using iostream header only.

C++ Excluding non-integer user inputs

I am making a number-guessing game where the user is asked to input a four-digit number. It is possible, however, that the user inputs less or more than four digits and/or a non-integer input (i.e. invalid input). My code stores the user input into an integer-type array. I just realized now that my code will still recognize "invalid inputs" as valid since the array where the input is being stored is declared as an integer-type. Below is a portion of my code:
#include <iostream>
using namespace std;
void guess(int num_guess[], int size);
int main(){
int list[4];
guess(list, 4);
for(int i = 0; i < 4; i++){
cout << list[i];
}
cout << endl;
}
void guess(int num_guess[], int size){
int number;
cin >> number;
for(int i = size-1; i >= 0; i--){
num_guess[i] = number%10;
number /= 10;
}
}
cout << list[i]; isn't really part of the original code, but this was how I found out that invalid inputs are still accepted. I encountered a similar problem before when I was making a rational roots calculator program in Python, but it was much easier then to detect and exclude unwanted inputs. My question is, how do I fix my code so that it can detect invalid inputs and output something like "Invalid input" and then proceed to ask the user for another input.
The following is a function to check if a string is a 4 digit positive integer. If the number could be negative, you just need to check if the s[0] == '-'.
bool check(string &s){
if(s.size() != 4) return false;
for(int i=0; i < 4; i++){
if(s[i] < '0' || s[i] > '9') return false;
}
return true;
}
The following is a function to convert a string to an int:
#include <stringstream>
int strToInt(string &s){
stringstream ss(s);
int ans;
ss >> ans;
return ans;
}
To exclude non integer inputs try the following:
void skip_to_int(){
// if is not an integer
if(cin.fail()){
// check character type
cin.clear();
char ch;
while(cin>>ch){
// throw away non digits
if(isdigit(ch)){
// put back if digit to be written
cin.unget();
return;}
}
}
else error ("no input");
}
And your input prompt function will look like this:
cout << "Please enter an integer" << endl;
int n=0;
if(cin>>n){
// integer OK, proceed
}
else{
cout << "That was not a numeric value, try again." << endl;
skip_to_int();}
Here's my solution. Beware, it uses C++11. Certainly not necessary if you use std::stringstream, but this should work pretty well.
I presume you don't want negative numbers. I also presume that any number of 0's in front doesn't make the number a 4-digit number. It will cut off padded 0's, so 01234 is a 4 digit number, but 0123 isn't.
void guess(int num_guess[], int size)
{
int number;
// if the length of the number isn't 4, try again until it is
do {
std::cin >> number;
if(std::to_string(number).length() != size)
std::cout << "You messed up the input. How hard could it be? Try again..." << std::endl;
} while(std::to_string(number).length() != size);
// by now, the size is definitely 4. insert it by digit into num_guess
for(int i = size-1; i >= 0; i++) {
num_guess[i] = number%10;
number /= 10;
}
}
#include <iostream>
#include <limits>
int main() {
int i = 0;
std::cout << "Please enter a number with four digits: ";
while( !(std::cin >> i) || !(i / 1000.0f >= 1.0f) )
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid entry." << std::endl;
std::cout << "Please enter a number with four digits: ";
}
}
the std::cin.clear() clears all errors flags on current stream structure and std::cin.ignore() cleans up the input stream itself. Once we don't know the size of stream 'til this operation I have used the maximum possible value of a stream size to make sure any stream length could be cleaned.
add #include "math.h"
and change guess
void guess(int num_guess[], int size){
int number = 0;
bool firstTime = true;
do
{
if (!firstTime)
cout << " Error, try again " << endl;
firstTime = false;
cin >> number;
} while (number<pow(10, size-1) || number>=pow(10, size));
for(int i = size-1; i >= 0; i--){
num_guess[i] = number%10;
number /= 10;
}
}

How can I limit my Array to only a size of however many values are entered, when the maximum number possible to enter is 1000?

#include <iostream>
using namespace std;
void displayListValues(int Array[], int Max)
{
int counter = 0;
for (int i = 0; i < Max; i++)
{
cout << counter << " = " << Array[i] << endl;
counter++;
}
}
void main()
{
const int Max = 1000;
int Array[Max]; // this is where I couldn't figure out what to change so the array isn't so huge
int counter = 0;
cout << "Enter Numbers. If finished, enter a negative number to continue" << endl;
do
{
cin >> Array[counter];
if (Array[counter] < 0)
break;
} while (counter < Max);
displayListValues(Array, Max);
}
details details details, any assistance would be fantastic!!! Thanks guys!!!! :D :D :D
I don't know what else to include in here because it keeps saying my post is mostly code. I apologize for this nonsensical gibberish at the bottom of the post.
Short answer is you can't. C/C++ arrays are a fixed size once defined.
The long answer is you need to use something other than an array. You should use a std::vector, this behaves similar to an array but can be resized.