I'm trying to make a program that asks the user to input a string then checks to see how many vowels and consonants are in the string, using c strings. Right now I'm working on the function that counts the vowels. I finally got it to were I don't have any errors, but my program just hangs up after choosing to count the vowels. Here is my code.
#include "stdafx.h"
#include <iostream>
#include <string.h>
using namespace std;
class VowelsandConsonants {
public:
int findVowels(char *cString, const int STRINGLEN) {
const int SIZE = STRINGLEN;
int vowelCount = 0;
char *str = cString;
char vowels[5] = { 'a', 'e', 'i', 'o', 'u' };
for (int i = 0; i < SIZE; i++) {
str[i];
for (int j = 0; j < SIZE; i++) {
vowels[j];
if (strcmp(vowels, str)) {
vowelCount++;
}
}
}
return vowelCount;
}
};
int main()
{
char *myString = nullptr;
const int STRLEN = 20;
int selection;
myString = new char[STRLEN];
VowelsandConsonants v;
cout << "Enter a string 20 characters or less." << endl;
cin.getline(myString, STRLEN);
cout << "Select the number of what you want to do." << endl;
cout << "1.) Count the number of vowels." << endl;
cout << "2.) Count the number of consonants." << endl;
cout << "3.) Count both vowels and consonants." << endl;
cout << "4.) Enter another string." << endl;
cout << "5.) Exit program." << endl;
cin >> selection;
if (selection == 1) {
cout << v.findVowels(myString, STRLEN);
}
delete[] myString;
return 0;
}
Am I approaching this the right way?
I recommend using a C-Style string containing the vowels, then using strchr to search it:
const char vowels[] = "aeiou";
const size_t length = strlen(cString);
unsigned int vowel_count = 0;
for (unsigned int i = 0; i < length; ++i)
{
if (strchr(vowels, cString[i]) != NULL)
{
++vowel_count;
}
}
There are other methods, such as using an array to hold the counts (and using the letter as an index) or std::map.
Related
For an assignment, we were to fill an array with user-defined characters that stops filling once the user enters a full stop ".". Part of the assignment is to print out the characters entered in the array in reverse, but what I have seems to just print nothing.
First time asking, so apologies if it's a silly question. Thanks in advance.
#include <iostream>
using namespace std;
//Function declarations
bool fillArray(char charArray[], int arraySize, int& numberUsed);
void outputInReverse(const char charArray[], int& numberUsed);
int main() {
const int arraySize = 100;
char charArray[arraySize] = { };
int numberUsed = 0;
//Function calls
cout << "\nFILLING ARRAY....\n";
fillArray(charArray, arraySize, numberUsed);
cout << "\nARRAY OUTPUT....\n";
outputInReverse(charArray, numberUsed);
}
//Function definitions
bool fillArray(char charArray[], int arraySize, int& numberUsed) {
char inputChar;
int index = 0;
const char sentinel = '.';
bool sentinelEntered = false;
bool arrayFull = false;
int count = 0;
//Take user input
for (int i = 0; i < arraySize; i++) {
if ((!sentinelEntered)) {
cout << "Enter up to " << arraySize << " character values. Enter full stop to end. " << "Enter char " << (i + 1) << ": " << endl;
cin >> inputChar;
charArray[index] = inputChar;
//How many entries made
numberUsed = i;
count++;
if ((inputChar == sentinel)) {
sentinelEntered = true;
cout << "Number of entries: " << (count - 1) << endl;
return count;
}
}
}
if (numberUsed == arraySize) {
arrayFull = true;
return arrayFull;
}
return sentinelEntered;
return count;
}
// Reverse
void outputInReverse(const char charArray[], int& numberUsed) {
for (int i = numberUsed; i > 0; i--) {
cout << "Output in reverse: " << charArray[i] << endl;
}
}
FILLING ARRAY....
Enter up to 100 character values. Enter full stop to end. Enter char 1:
a
Enter up to 100 character values. Enter full stop to end. Enter char 2:
b
Enter up to 100 character values. Enter full stop to end. Enter char 3:
c
Enter up to 100 character values. Enter full stop to end. Enter char 4:
d
Enter up to 100 character values. Enter full stop to end. Enter char 5:
e
Enter up to 100 character values. Enter full stop to end. Enter char 6:
.
Number of entries: 5
ARRAY OUTPUT....
Output in reverse:
Output in reverse:
Output in reverse:
Output in reverse:
Output in reverse:
Not sure what you are trying to return from fillArray(), but since its a bool type, assuming you are trying to return if the array is empty or not. Observe added comments to see corrections.
int main() {
const int arraySize = 100;
//corrected
char charArray[arraySize] = { NULL };
int numberUsed = 0;
//Function calls
cout << "\nFILLING ARRAY....\n";
fillArray(charArray, arraySize, numberUsed);
cout << "\nARRAY OUTPUT....\n";
outputInReverse(charArray, numberUsed);
return 0;
}
bool fillArray(char charArray[], int arraySize, int& numberUsed) {
char inputChar;
int index = 0;
const char sentinel = '.';
bool sentinelEntered = false;
bool arrayFull = false;
int count = 0;
//Take user input
for (int i = 0; i < arraySize; i++) {
if ((!sentinelEntered)) {
cout << "Enter up to " << arraySize << " character values. Enter full stop to
end. " << "Enter char " << (i + 1) << ": " << endl;
cin >> inputChar;
//corrected: shifted here so before '.' can enter into array we return
if ((inputChar == sentinel)) {
sentinelEntered = true;
cout << "Number of entries: " << (count) << endl;
//correction: update numberUsed before returning and no of
//elements = count
numberUsed = i;
return count;
}
//correction: array index should not be "index" but i
charArray[i] = inputChar;
//How many entries made
numberUsed = i;
count++;
}
}
if (numberUsed == arraySize)
return true;
return false;
}
void outputInReverse(const char charArray[], int& numberUsed) {
for (int i = numberUsed-1; i >= 0; i--) {
cout << "Output in reverse: " << charArray[i] << endl;
}
}
I've tried so many times in different way to concatenate two strings, one way gives me segment fail,and the other way don't give me error but not it's making the correct function of concatenate. I need result is like this aa, what am I doing wrong?
#include <iostream>
using namespace std;
char str1[20], str2[20], str3[20];
void stringConcat(char[], char[], char[]);
void stringConcat(char str1[], char str2[], char str3[])
{
int i = 0, j = 0;
if (str1[i] != '\0') {
str3[i] = str1[i];
i++;
}
if (str2[j] != '\0') {
str3[i + j] = str2[j];
j++;
}
str3[i] = '\0';
}
int main()
{
int compare;
cout << "First string" << endl;
cin >> str1;
cout << "Second string" << endl;
cin >> str2;
stringConcat(str1, str2, str3);
cout << "result: " << str3 << endl;
return 0;
}
#include <string.h>
#include "BubbleSort.h"
void BubbleSort(char Str[])
{
int i;
int NumElements;
bool Sorted;
char Temp;
NumElements = strlen(Str);
do {
Sorted = true;
NumElements--;
for (i = 0; i < NumElements; i++)
if (Str[i] > Str[i + 1])
{
Temp = Str[i];
Str[i] = Str[i + 1];
Str[i + 1] = Temp;
Sorted = false;
}
} while (!Sorted);
}
/////////////////////////////////////////////
#include <iostream>
#include "Bubblesort.h"
using namespace std;
void main() {
int Num;
char Array[20];
cout << "How many numbers would you like to enter?" << endl;
cin >> Num;
cout << "Enter your numbers:" << endl;
for (int i = 0; i < Num; i++)
{
cin >> Array[i];
}
cout << "Here are the numbers you entered:" << endl;
for (int i = 0; i < Num; i++)
{
cout << Array[i] << " ";
}
cout << endl << endl;
BubbleSort (Array);
cout << "Here are your sorted numbers:" << endl;
for (int i = 0; i < Num; i++)
{
cout << Array[i] << " ";
}
cout << endl;
}
////////////////////////////////////////////////////////
#ifndef BUBBLE_SORT_H
#define BUBBLE_SORT_H
void BubbleSort(char[]);
#endif
I get a Run Time Error stating that Num was corrupted. Can anyone help pinpoint the problem in my code?
Thanks
char Array[20] while the Num you input is larger than 20, it will corrupt.
Better use vector and push_back
One mistake is that you're calling strlen on a char array that is not guaranteed to be NULL terminated:
NumElements = strlen(Str);
Thus NumElements has an undetermined value.
You need to either:
1) pass the actual number of characters that are to be sorted as a parameter, along with the array and getting rid of the call to strlen:
BubbleSort(Array, Num);
//...
void BubbleSort(char Str[], int NumElements)
or
2) Make sure the char array you're passing is null terminated
Why the example code below can run fine on Visual Studio. In Eclipse, NetBean or CodeBlock the code can run but can't show the Result? Thanks All.
Ex: input one string.
a/ Uppercase first letter.
b/ Remove spaces inside the string.
#include "iostream"
#include "string.h"
using namespace std;
#define MAX 255
//uppercase first letter
char* Upper(char* input)
{
char* output = new char[MAX];
bool isSpace = false;
for (int i = 0; i < strlen(input); i++)
{
output[i] = input[i];
if (isSpace)
{
output[i] = toupper(output[i]);
isSpace = false;
}
if (output[i] == ' ') isSpace = true;
}
output[strlen(input)] = '\0'; // end of the string
output[0] = toupper(output[0]); // first character to upper
return output;
}
//remove space inside the string
char* RemoveSpaceInside(char* input)
{
char* output = new char[MAX];
strcpy(output, input);
int countWhiteSpace = 0;
for (int i = 0; i < strlen(output); i++)
{
if (output[i] == ' ')
{
for (int j = i; j < strlen(output) - 1; j++) // move before
{
output[j] = output[j + 1];
}
countWhiteSpace++;
}
}
output[strlen(output) - countWhiteSpace] = '\0'; // end of the string
return output;
}
int main()
{
char* name = new char[MAX];
cout << "Enter name: "; cin.getline(name, strlen(name));
cout << "Your name: " << name << endl;
cout << "\n******* Q.A *******\n";
char* qa = Format2VN(name);
cout << qa << endl;
cout << "\n******* Q.B *******\n";
char* qb = RemoveSpaceInside(name);
cout << qb << endl;
return 0;
}
char* name = new char[MAX];
cout << "Enter name: ";
cin.getline(name, strlen(name));
Calling strlen(name) will invoke undefined behavior, because you haven't initialized the array. Poor strlen will try to find the NUL character in an uninitialized byte mess. Definitely not a good idea.
What you probably want is:
cin.getline(name, MAX); // not sure if MAX or MAX-1 or whatever
In general, do yourself a favor and replace char* with std::string. Also, get a good C++ book.
Here is how your example would look like in actual C++:
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
std::string upper_first_letter(std::string s)
{
if (!s.empty()) s[0] = toupper(s[0]);
return s;
}
std::string remove_spaces(std::string s)
{
s.erase(std::remove_if(s.begin(), s.end(), isspace), s.end());
return s;
}
int main()
{
std::string name;
std::cout << "Enter name: ";
std::getline(std::cin, name);
std::cout << name << '\n';
std::cout << upper_first_letter(name) << '\n';
std::cout << remove_spaces(name) << '\n';
}
So right now I have this code that generates random letters in set increments determined by user input.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int sLength = 0;
static const char alphanum[] =
"0123456789"
"!##$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
int main()
{
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
while(true)
{
for (int x = 0; x < sLength; x++)
{
cout << genRandom();
}
cout << endl;
}
}
I'm looking for a way to store the first (user defined amount) of chars into a string that I can use to compare against another string. Any help would be much appreciated.
Just add
string s(sLength, ' ');
before while (true), change
cout << genRandom();
to
s[x] = genRandom();
in your loop, and remove the cout << endl; statement. That will replace all of the printing by putting the characters into s.
Well, how about this?
std::string s;
for (int x = 0; x < sLength; x++)
{
s.push_back(genRandom());
}
#include<algorithm>
#include<string>
// ...
int main()
{
srand(time(0)); // forget me not
while(true) {
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
string r(sLength, ' ');
generate(r.begin(), r.end(), genRandom);
cout << r << endl;
}
}