Pig latin conversion using Cstrings - c++

The program takes in a word given by the user and translates that to pig latin. I've gotten everything to work almost perfectly, but have run into two bugs. The first of which is when translating words that begin with consonants say "count", the output is "ounttcay" instead of "ountcay". The second bug is that when for three letter words like "egg" or "not" the output is "egg_\377ay" or "ottn\377ay". Is there a simple way to remove that duplicate character and get rid of those numbers?
Note - Unfortunately it has to be done using a Cstring
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int convertToPigLatin(char arr[50]);
bool isVowel(char ch);
int main() {
char userInput[50];
char answer = ' ';
do {
cout << "Enter a word to convert it to pig latin" << endl;
cin.getline(userInput, 50); //get user input
cout << "Your entered word is " << userInput << endl;
convertToPigLatin(userInput); //translate user's input into piglatin
cout << "Would you like to convert another word?" << endl;
cin >> answer;
cin.ignore(); //clear past user input
cin.clear();
} while (answer == 'Y' || answer == 'y');
return 0;
}
bool isVowel (char ch) {
switch (tolower(ch)) { //if the first character of the given input is a vowel
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
int convertToPigLatin(char arr[50]) {
char newArr[50];
// string conjunctions[6] = {"and","but","for","nor","yet","the"}; //list of conjunctions not to be converted
size_t arrLength = strlen(arr); //holds length of input
for (int i = 0; i < arrLength; i++) { //make sure all characters in input are lower case for easier processing
newArr[i] = tolower(arr[i]);
}
char lastChar = newArr[0]; //save the first character in case it needs to be appended
if (atoi(arr) || arr[0] == '\0') { //if the input contains a number or begins with a null character print an error
cout << "Cannot translate inputs that contain numbers" << endl;
return -1;
} else if (arrLength <= 2) { // if the input is 2 or less characters
cout << newArr << endl; //print the input as is
cout << "Boring! Try somthing more than 2 characters long" << endl;
return 0;
} else if ((strstr(newArr, "and") && arrLength == 3) || (arrLength == 3 && strstr(newArr, "but")) || (arrLength == 3 && strstr(newArr, "for")) || (arrLength == 3 && strstr(newArr, "nor")) || (arrLength == 3 && strstr(newArr, "yet")) || (arrLength == 3 && strstr(newArr, "the"))) { //if the input is more than 2 characters long
cout << newArr << endl; //print the input as is
cout << "No conjucntions try again!" << endl;
return 0;
} else { //if the given input is three characters and is not a conjunction, being translation
if (isVowel(arr[0])) { //check if input's first character is a vowel
cout << "Your word in piglatin is "<< strcat(newArr, "ay") << endl; //print that string with 'ay' at the end (i.e. egg'ay')
return 0;
} else { //else if the given input starts with a consonant
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
newArr[arrLength] = lastChar;
}
cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;
return 0;
}
}
return 0;
}

You're not terminating newArr, and the last index of the input string is arrLength - 1.
int convertToPigLatin(char arr[50]) {
// Make sure newArr is properly terminated.
char newArr[50] = {0};
// [...]
} else { //else if the given input starts with a consonant
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
}
// Do this outside the loop.
newArr[arrLength-1] = lastChar;
// No need for strcat here.
cout << "Your word in piglatin is " << newArr << "ay" << endl;
}
}
return 0;
}

You need to add the '\0' at the end of newArr because strlen does not count it so you are not copying it. strcat replaces '\0' witn 'ay\0' but you have no '\0'.
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
newArr[arrLength] = lastChar;
}
newArr[arrLength+1] = '\0';
cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;

Related

English to Morse code program

#include <iostream>
#include <iomanip>
#include <conio.h>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
string text[39] = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","Stop",",","?"};
string code[39] = {".-","-...","-.-.","-..",".","..-","--.","....","..",".---","-.-",".-..","--",
"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",
".----","..---","...--","....-",".....","-....","--....","---..","----.","-----",".-.-.-","--..--","..--.."};
string English, Morse, output_string;
int option, string_size = 0, location;
char again = 'y', letter;
while(again == 'y')
{
system("cls");
cout << "1 - Encode(Text to Morse)\n";
cout << "2 - Decode(Morse Code to Text)\n";
cout << "3 - Display the Morse Code\n";
cout << "4 - Quit\n";
cout << "Enter 1,2,3 or 4:";
cin >> option;
cin.ignore(256,'\n');
system("cls");
switch(option)
{
case 1:
cout << "\nEnter a string with multiple words to encode:";
getline(cin, English);
system("cls");
cout << "\nThe target string to be translated is:" << "\n";
cout << English << "\n";
string_size = English.length();
for(int n = 0; n <= string_size-1; n++)
{
letter = (char)English.at(n);
if(letter != ' ')
{
for(int t = 0; t <=39; t++)
{
if(letter == text[t])
{
cout << code[t] << " ";
break;
}
}
}
else if(letter == ' ')
{
cout << "\n";
}
}
getch();
break;
}
}
}
I didn't finish it yet, but I don't know why I can't run if(letter == text[t]), it says it's an error. how can I fix it? And I have no idea to write the code that Morse to English. how can I know the position of the array that the user entered?
Error message:
error: no match for 'operator==' (operand types are 'char' and 'std::string {aka std::basic_string}')|
You are trying to compare between strings and char.
You need to write the array like that (if you want to use just characters):
char text[39] = {'A','B','C','D','E','F','G','H','I','J','K','L','M'};
and not:
string text[39] = {"A","B","C","D","E","F","G","H","I","J","K","L","M"};
for (int t = 0; t <= 39; t++)
You have 39 items starting at zero index, therefore your loop should go up to (but not including) 39
for (int t = 0; t < 39; t++)
{
...
}
You can declare a temporary string to copy each letter to string. You would also need to make sure text is upper case:
letter = (char)English.at(n);
if (letter != ' ')
{
for (int t = 0; t < 39; t++)
{
std::string temp;
temp = toupper(letter);
if (temp == text[t])
{
cout << code[t] << " ";
break;
}
}
}
If you want the array to be string - then use strcmp() function.
if(strcmp(text[t],letter)==0)
{
cout << code[t] << " ";
break;
}
Have a good luck!

Can someone tell me why I am stuck in my validation loop after entering 'y' to continue?

Why am I getting stuck in my validation loop after hitting Y to continue? I have to use cin.get and can not use strings
This program collects input from a user and displays them by using a pointer with an array, I have to validate for negative numbers, letters and newline characters with the appropriate message
#include <iostream>
#include <iomanip>
using namespace std;
void validateUserInput(char *userInputCharArray, int &strLength);
int const ARRAY_SIZE = 100;
int main()
{
char *userInputCharArray = nullptr;
char yes = NULL;
int lengthOfInput;
//creating a dynamic array size 100
userInputCharArray = new char[ARRAY_SIZE];
//loop
do
{
int count = 0;
//user prompt and accept input
cout << "Please enter an integer >= 0 and press <ENTER>: " << endl;
cin.get(userInputCharArray, ARRAY_SIZE);
while(userInputCharArray[count] != ' ' && userInputCharArray[count] != '\0')
count++;
{
if(userInputCharArray[count] == ' ')
{
userInputCharArray[count] = '\0';
}
}
lengthOfInput = count;
validateUserInput(userInputCharArray, lengthOfInput);
cout << "Your number is: " << endl;
for(int i = 0; i < lengthOfInput; i++)
{
cout << userInputCharArray[i] - '0' << " ";
}
cout << endl;
cout << "Press y to continue or any other button to exit: " <<endl;
cin >> yes;
delete [] userInputCharArray;
userInputCharArray = nullptr;
userInputCharArray = new char[ARRAY_SIZE];
}while(yes == 'y' || yes == 'Y');
cout << "Thank you Good-Bye";
cout << endl;
delete [] userInputCharArray;
userInputCharArray = nullptr;
system("pause");
return 0;
}
Im getting stuck in my functions while loop
void validateUserInput(char *userInputCharArray, int &strLength)
{
int counter = 0;
while(*userInputCharArray < '0' || (*userInputCharArray >= 'A' && *userInputCharArray <= 'Z')
|| (*userInputCharArray >= 'a' && *userInputCharArray <= 'z')
|| *userInputCharArray == 0)
{
cout << "Please enter a positive integer and press <ENTER>: " <<endl;
cin.get(userInputCharArray, ARRAY_SIZE);
}
while(userInputCharArray[counter] != ' ' && userInputCharArray[counter] != '\0')
counter++;
if(userInputCharArray[counter] == ' ')
{
userInputCharArray[counter] = '\0';
}
strLength = counter;
}
According to the while loop you have here, you will keep on calling in.get so long as the first character that you read in is a digit or an alphabetic character. So, if you start your input with one of those characters, you will loop forever.
I'd suggest that you get input a line at a time and then parse what you get.
cin.get(*userInputCharArray);
Will extract one character only, therefore the terminator character '\0' will not be part of userInputCharArray.
Change it to read a line at a time and parse the input. If you're still having issues, you can flush your input buffer before each read like so:
cin.ignore(10, "\n");
cin.get(userInputCharArray, ARRAY_SIZE);

How to remove punctuation characters from a char array?

My program prompts a user for a phrase to check if its a palindrome, then it's supposed to print out the phrase without capitalization or special characters like " ' , ? etc. My problem is erasing those characters. I've gotten my program to ignore them I'm asking how should I erase them? I made a comment where I think the statement should go. Example output should be: "Madam I'm Adam" to "madamimadam"
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
//Variables and arrays
int const index = 80;
char Phrase[index];
char NewPhrase[index];
int i, j, k, l;
bool test = true;
//Prompt user for the phrase/word
cout << "Please enter a sentence to be tested as a palindrome: ";
cin.getline(Phrase, 80);
//Make everything lowercase, delete spaces, and copy that to a new array 'NewPhrase'
for(k = 0, l = 0; k <= strlen(Phrase); k++)
{
if(Phrase[k] != ' ')
{
NewPhrase[l] = tolower(Phrase[k]);
l++;
}
}
//cout << "The Phrase without punctuation/extra characters: " << newPhrase[l];
int length = strlen(NewPhrase); //Get the length of the phrase
for(i = 0, j = length-1; i < j; i++, j--)
{
if(test) //Test to see if the phrase is a palindrome
{
if(NewPhrase[i] == NewPhrase[j])
{;}
else
{
test = false;
}
}
else
break;
}
if(test)
{
cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
cout << "The Palindrome is: " << NewPhrase << endl << endl;
}
else
cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;
system("Pause");
return 0;
}
Modify this line:
if(Phrase[k] != ' ')
To be:
if((phrase[k] != ' ') && (ispunct(phrase[k]) == false))
This means that we check for spaces and punctuation at the same time.
Also, consider rewriting this:
if(NewPhrase[i] == NewPhrase[j])
{;}
else
{
test = false;
}
As this:
if(NewPhrase[i] != NewPhrase[j])
test = false;
Here's suggestion:
Use an std::string
Use std::ispunct to determine whether a character in the string is a punctuation mark
Use the erase-remove idiom to remove punctuation
That is one line of code (plus one extra line for a convenience lambda):
std::string phrase = .....;
auto isPunct = [](char c) { return std::ispunct(static_cast<unsigned char>(c)); }
phrase.erase(std::remove_if(phrase.begin(), phrase.end(), isPunct),
phrase.end());
Next, for turning into lower case, from my answer to this recent question, another one-liner:
std::transform(phrase.begin(), phrase.end(), phrase.begin(),
[](char c)
{ return std::tolower(static_cast<unsigned char>(c));});

probably wrong if statement, not moving to next row after input

When I run my program, I have to type how many rows do I want in my output. I have a limit from 1 to 100 rows. Each row is a task with a name of the task followed by increasing number, example: Task1:, Task2, .... When I type something into input, it must convert input string /see the code below - except the code in main();/.
My problem is that when I type first input, it should go to next task/next row/ but it doesnt. I type for example 10 strings but they dont go each to next task but they stay in one task..hope you understand now.
#include<iostream>
#include<string>
#include <ctype.h>
using namespace std;
void Convert(string input){
string output = "";
string flag = "";
bool underscore = false;
bool uppercase = false;
if ( islower(input[0]) == false){
cout << "Error!" <<endl;
return;
}
for (int i=0; i < input.size(); i++){
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
cout << "Error!" <<endl;
return;
}
if (islower(input[i])){
if (underscore){
underscore = false;
output += toupper(input[i]);
}
else
output += input[i];
}
else if (isupper(input[i])){
if (flag == "C" || uppercase){
cout << "Error!"<<endl;
return;
}
flag = "Java";
output += '_';
output += tolower(input[i]);
}
else if (input[i] == '_'){
if (flag == "Java" || underscore){
cout << "Error!" <<endl;
return;
}
flag = "C";
underscore = true;
}
}
cout << output <<endl;
}
int main(){
const int max = 100;
string input;
int pocet_r;
cout << "Zadaj pocet uloh:" << endl;
cin >> pocet_r;
if(pocet_r >= 1 && pocet_r <=100)
{
for (int i = 0; i <pocet_r; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
while (cin >> input)
Convert (input);
while(input.size() > max)
cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
while(input.size() > max)
cin >> input;
while (cin >> input)
Convert(input);
}
}else{
cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}
Your first if in Convert will always fail on a non-underscore and return. I don't think that's what's intended. Agree with other answer on the while cin loop. The next two whiles should be if's apparently. Step thru this code with a debugger and watch it line by line and see where it fails. You've got multiple issues here, and I'm not entirely sure what the intent is.
Edit - I didn't parse the extra parenthesis correctly. The first if in convert is actually okay.

C++ code compiles, but gives wrong output....initialize function is wrong?

I understand that declarations are missing, the code compiles fine however, the output does not output correctly... instead of a letter, I am getting ¿ instead. I believe the problem is in the initialize function, I just cannot seem to figure out what it is....
void printResult(ofstream& outFile, letterType letterList[], int listSize)
{
int i;
int sum = 0;
double Percentage = 0;
cout << "PRINT" << endl;
for (i = 0; i < 52; i++)
sum += letterList[i].count;
outFile << fixed << showpoint << setprecision(2) << endl;
outFile << "Letter Count Percentage of Occurrence" << endl;
for (i = 0; i < 52; i++)
{
outFile << " " << letterList[i].letter << " "
<< setw(5) << letterList[i].count;
if (sum > 0)
Percentage = static_cast<double>(letterList[i].count) /
static_cast<double>(sum) * 100;
/*
Calculates the number of Occurrence by dividing by the total number of
Letters in the document.
*/
outFile << setw(15) << Percentage << "%" << endl;
}
outFile << endl;
}
void openFile(ifstream& inFile, ofstream& outFile)
{
string inFileName;
string outFileName;
cout << "Enter the path and name of the input file (with extension): ";
getline(cin, inFileName);
inFile.open(inFileName);
cout << endl;
cout << "Your input file is " << inFileName << endl;
cout << endl;
cout << "Enter the path and name of the output file (with extension): ";
getline(cin, outFileName);
outFile.open(outFileName);
cout << endl;
cout << "The name of your output file is " << outFileName << endl;
cout << endl;
}
void initialize(letterType letterList[])
{
//Loop to initialize the array of structs; set count to zero
for(int i = 0; i < 26; i++)
{
//This segment sets the uppercase letters
letterList[i].letter = static_cast<char>('A' + i);
letterList[i].count = 0;
//This segment sets the lowercase letters
letterList[i + 26].letter = static_cast<char>('a' + i);
letterList[i + 26].count = 0;
}
}
void count(ifstream& inFile, letterType letterList[], int& totalBig, int& totalSmall)
{
cout << "COUNT WORKING" << endl;
char ch;
//read first character
inFile >> ch;
//Keep reading until end of file is reached
while( !inFile.eof() )
{
//If uppercase letter or lowercase letter is found, update data
if('A' <= ch && ch <= 'Z')
{
letterList[static_cast<int>(ch) - 65].count++;
}
else if('a' <= ch && ch <= 'z')
{
letterList[static_cast<int>(ch) - 97].count++;
}
//read the next character
inFile >> ch;
} //end while
} //end function
===============
driver code
int main()
{
struct letterType letterList[52]; //stores the 52 char we are going to track stats on
int totalBig = 0; //variable to store the total number of uppercase
int totalSmall = 0; //variable to store the total number of lowercase
ifstream inFile;
//defines the file pointer for the text document
ofstream outFile;
//the file pointer for the output file
cout << "MAIN WORKING" << endl;
openFile(inFile, outFile);
//allow the user to specify a file for reading and outputting the stats
/*if (!inFile || !outFile)
{
cout << "***ERROR*** /n No such file found" << endl;
return 1;
}
else
return 1;
*///Check if the files are valid
initialize(&letterList[52]);
//initalizes the letter A-Z, and a-z */
count(inFile, &letterList[52], totalBig, totalSmall);
// counts the letters
printResult(outFile, letterList, 52);
//writes out the stats
//Close files
inFile.close();
outFile.close();
return 0;
}
=====================
Entire Count function
void count(ifstream& inFile, letterType letterList[], int& totalBig, int& totalSmall)
{
cout << "COUNT WORKING" << endl;
char ch;
//read first character
inFile >> ch;
//Keep reading until end of file is reached
while( !inFile.eof() )
{
//If uppercase letter or lowercase letter is found, update data
if('A' >= ch && ch <= 'Z')
{
letterList[ch - 'A'].count++;
}
else if('a' >= ch && ch <= 'z')
{
letterList[(ch - 'a') + 26].count++;
}
//read the next character
inFile >> ch;
} //end while
} //end function
The count logic is confusingly written and that is masking one bug (where it folds the case):
if('A' <= ch && ch <= 'Z')
{
letterList[static_cast<int>(ch) - 65].count++;
}
else if('a' <= ch && ch <= 'z')
{
letterList[static_cast<int>(ch) - 97].count++; // <--- a bug here
}
This reacts to 'a' by incrementing the count for the first element, which looks like it is intended to be the count for 'A'. This is easily fixed by offsetting lowercase, also rewriting it so it is clearer what is being done:
if ('A' <= ch && ch <= 'Z')
{
letterList[static_cast<int>(ch - 'A')].count++; // count uppercase
}
else if ('a' <= ch && ch <= 'z')
{
letterList[static_cast<int>(ch - 'a') + 26].count++; // count lowercase
}
As for the main bug, initialize() is not called anywhere.
Initialize is being called incorrectly as initialize(&letterList[52]); This attempts to initialize entries 52, 53, ... 103. I am surprised it doesn't segfault.
It should be called as
initialize(letterList);
Your functions are doing just right.
In your driver code you are calling these functions with wrong argumnets
Check these lines they should be like this
initialize(&letterList[0]);
//initalizes the letter A-Z, and a-z */
count(inFile, &letterList[0], totalBig, totalSmall);
While passing letterList array to the functions you should pass the pointer to first element in the array. you should pass &letterList[0] or simply letterList