Trouble with whole sentence manipulation - c++

Im making a pig latin converter, I can get it to manipulate one word and need it to convert whole sentences, making each word outputted in pig latin, below is my code:
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;
bool isVowel (char);
string rotate(string);
string plString(string);
int main()
{
string str;
cout <<"Enter a sentence: ";
getline (cin, str);
cout << endl;
cout << str <<" in pig latin - " << plString(str) << endl;
ifstream infile;
infile.open("input.txt");
infile >> str;
while(infile)
{
cout << plString(str) << " ";
infile >> str;
}
cout << endl;
}
bool isVowel (char ch)
{
switch (ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return true;
default:
return false;
}
}
string rotate(string str)
{
string::size_type len = str.length();
string str1;
str1 = str.substr(1, len - 1) + str[0];
return str1;
}
string plString(string str)
{
string::size_type len;
bool vowel;
string::size_type counter;
if (isVowel (str[0]))
str = str + "way";
else
{
str = str + "";
str = rotate(str);
len = str.length();
vowel = false;
for (counter = 1; counter < len - 1; counter++)
if (isVowel (str[0]))
{
vowel = true;
break;
}
else
str = rotate(str);
if(!vowel)
str = str.substr(1,len) + "way";
else
str = str + "ay";
}
return str;
}
any advice on how to get this to do full sentences would be greatly appreciated!

You would need to split your string into words (splitting by white space delimiter). Maybe this would help if you insert it after the getline call instead of the " in pig latin - " line:
char delimiter = ' ';
string::size_type i = 0;
string::size_type j = str.find(delimiter);
while (j != string::npos) {
string word = str.substr(i, j-i);
std::cout << plString(word) << std::endl;
i = ++j;
j = str.find(delimiter, j);
if (j == string::npos) {
word = str.substr(i, s.length());
std::cout << plString(word) << std::endl;
}
}

Related

Trouble with morse code spaces between words

I am having trouble trying to get my code to convert a space character to 'xx'. I have it set so after every letter there is an x to separate the letters but I can't quite get what I have below to work for a space between words.
#include <iostream>
#include <cstring>
#include <sstream>
#include <algorithm>
using namespace std;
string translate(string word)
{
string morseCode[] = { ".-x", "-...x", "-.-.x", "-..x", ".x", "..-.x",
"--.x", "....x", "..x", ".---x", "-.-x", ".-..x", "--x", "-.x", "---x",
".--.x", "--.-x", ".-.x", "...x", "-x", "..-x", "...-x", ".--x", "-..-x",
"-.--x", "--..x" };
char ch;
string morseWord = " ";
//string morseWord = " " == "xx";
for (unsigned int i = 0; i < word.length(); i++)
{
if (isalpha(word[i]))
{
ch = word[i];
ch = toupper(ch);
morseWord += morseCode[ch - 'A'];
morseWord += morseCode[ch = ' '] == "xx";
//morseWord += "xx";
//morseWord += " " == "xx";
}
}
return morseWord;
}
int main()
{
stringstream stringsent;
string sentence;
string word = "";
cout << "Please enter a sentence: ";
getline(cin, sentence);
stringsent << sentence;
cout << "The morse code translation for that sentence is: " << endl;
while (stringsent >> word)
cout << translate(word) << endl;
system("pause");
return 0;
}
I've commented out all of the unnecessary bits.
#include <iostream>
// #include <cstring>
// #include <sstream>
#include <ccytpe> // You were relying on an include dependency; this is the
// library that contains isalpha()
using namespace std;
string translate(string word)
{
string morseCode[] = { ".-x", "-...x", "-.-.x", "-..x", ".x", "..-.x",
"--.x", "....x", "..x", ".---x", "-.-x", ".-..x", "--x", "-.x", "---x",
".--.x", "--.-x", ".-.x", "...x", "-x", "..-x", "...-x", ".--x", "-..-x",
"-.--x", "--..x" };
char ch;
string morseWord = " ";
//string morseWord = " " == "xx";
for (unsigned int i = 0; i < word.length(); i++)
{
if (isalpha(word[i]))
{
ch = word[i];
ch = toupper(ch);
morseWord += morseCode[ch - 'A'];
// morseWord += morseCode[ch = ' '] == "xx"; // Having a space
// character is
// impossible here
//morseWord += "xx";
//morseWord += " " == "xx";
}
else if (isspace(word[i])) // True for any whitespace character
{
morseWord += "xx";
}
}
return morseWord;
}
int main()
{
// stringstream stringsent;
string sentence;
// string word = ""; // should just be 'string word;'
// Default constructed strings are already empty
cout << "Please enter a sentence: ";
getline(cin, sentence);
// stringsent << sentence;
cout << "The morse code translation for that sentence is: " << endl;
cout << translate(sentence) << endl;
return 0;
}
Your problem was two-fold. A space character is not alphabetic, so no space character could ever enter your if block. Secondly, in sending only one word at a time, you were never even sending space characters to begin with.
Here's a sample output from the code above:
Please enter a sentence: hello world
The morse code translation for that sentence is:
....x.x.-..x.-..x---xxx.--x---x.-.x.-..x-..x

Pig Latin converter using toupper

I'm having trouble converting using toupper on the first character in my string.
I used tolower(first[0]) to turn the first letter into lower case.
Why doesn't toupper(first[0]) make the first character upper case?
Also, is there a way to move the first character in a string to the last spot?
Thanks a lot in advance.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char ans;
do{
string first, last;
char first_letter, first_letter2;
cout << "This program will convert your name "
<< "into pig latin.\n";
cout << "Enter your first name: \n";
cin >> first;
cout << "Enter your last name: \n";
cin >> last;
cout << "Your full name in pig latin is ";
for(int x = 0; x < first.length(); x++){
first[x] = tolower(first[x]);
}
for(int x = 0; x < last.length(); x++){
last[x] = tolower(last[x]);
}
first_letter = first[0];
bool identify;
switch (first_letter)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
identify = true;
break;
default:
identify = false;
}
if(identify == true){
toupper(first[0]);
cout << first << "way" << " ";
}
first_letter2 = last[0];
bool identify2;
switch (first_letter2)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
identify2 = true;
break;
default:
identify2 = false;
}
if(identify2 == true){
toupper(first[0]);
cout << last << "way" << endl;
}
cout << "You you like to try again? (Y/N)\n";
cin >> ans;
} while(ans == 'y' || ans == 'Y');
return 0;
}
Just a simple blunder, compare
first[x] = tolower(first[x]);
with
toupper(first[0]);
usual case of the 'can't see the obvious thing missing' syndrome... I hate those mistakes.
As for moving the first character to the end I'd usually just use substr() for a simple case:
str = str.substr(1) + str[0];

convert variable string into char array c++

I found so incredibly many question posts of this sort - i'm speaking of "convert string to char array" - but none of those solutions actually work for me, trying to convert cin >> text into some char array textArray[1024] which I could then convert into a list cause I think it's easier to work with.
The Problem is: Spaces. Every time when there's a space in there, it just skips the following actions and punches me with my own error messeges.
It's for some encryptor (code down below).
If there's any easier way of doing this then let me know.
#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include "encryptor.h"
using namespace std;
void encrypt()
{
string text;
char textArray[1024];
list<char> listText;
list<char>::iterator it;
int textSize;
string code;
bool fail = false;
string segment;
string fileName;
cout << "Now enter your text. (max 1024 chars)" << endl;
cin >> text;
textSize = text.size();
//string to char[]
//none of these work
strncpy(textArray, text.c_str(), sizeof(textArray));
textArray[sizeof(text) - 1] = 0;
strcpy_s(textArray, text.c_str());
for (int i = 0; i < text.length(); i++)
{
textArray[i] = text[i];
}
aText[text.length()] = '\0';
text.copy(textArray, text.length()+1);
//char[] to list
for(int i = 0; i < textSize; i++)
{
char *c = new char(textArray[i]);
listText.push_back(*c);
}
//Going through list
//for every char there's a special segment added to the string
for(it = listText.begin(); it != listText.end(); it++)
{
if(fail == true) break;
switch (*it)
{
case 'a':
case 'A':
{
segment = "XQ7";
} break;
{/*---*/} //I just let everything from b - z and 0 - 9 out for this post
case ' ':
{
segment = "Z 7";
} break;
case '.':
{
segment = "Z 8";
} break;
case ',':
{
segment = "Z 4";
} break;
default:
{
cout << "There's a special char this program doesn't understand. It is "
cout << *it << endl;
cout << "Do it again" << endl;
fail = true;
} break;
}
code = code + segment;
}
do
{
cout << "\n\nname of the file: ";
cin >> fileName;
if(fileName != "")
{
ofstream write;
write.open(fileName + ".txt");
write << code;
write.close();
} else {
cout << "Name shouldn't be empty!" << endl;
}
} while(fileName == "");
}
Your main issue is not in converting the string text to a character array but it is that you are not capturing the entire line from stdin.
The line cin >> text; will read from stdin until the first whitespace character has been met. That is why you are having issues with spaces. You are only reading characters into text up to the first whitespace character. Instead you need to use getline(). Replacing cin >> text; with getline(cin, text); will read in an entire line from stdin including any whitespace characters.
I've included a complete example to read in a line of text from stdin and convert it to a list of characters for you below. It completely skips the need to convert the string into a character array before converting it into a list.
#include <iostream>
#include <list>
#include <string>
using namespace std;
int main() {
string s;
list<char> text;
getline(cin, s);
for (string::iterator it = s.begin(); it != s.end(); ++it) {
text.push_back(*it);
}
// Verification
cout << "You entered " << text.size() << " characters\nThey were:\n";
for (list<char>::iterator it = text.begin(); it != text.end(); ++it) {
cout << *it;
}
cout << endl;
}

PigLatin C++ function

This code is giving me a lot of strange errors. For whatever reason, the "newstring" function is not running. I think it may have something to do with the fact that it is part of a cout statement, because if I remember correctly, it does not give the same error if I call the function independently of the cout statement. The program requires a string function, but the new function is not running for some reason. Could anyone take a look at the code?
#include <iostream>
#include <string>
using namespace std;
void newstring(string);
bool isVowel(char ch);
string rotate(string pStr);
string pigLatinString(string pStr);
int main()
{
string str;
cout << "Enter a sentence to be translated to Pig Latin: ";
getline(cin, str);
cout << endl;
cout << "The pig Latin form of " << str << " is: " << newstring(str);
system("PAUSE");
return 0;
}
bool isVowel(char ch)
{
switch(ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return true;
default:
return false;
}
}
string rotate(string pStr)
{
string::size_type len = pStr.length();
string rStr;
rStr = pStr.substr(1, len - 1) + pStr[0];
return rStr;
}
string pigLatinString(string pStr)
{
string :: size_type len;
bool foundVowel;
if (isVowel(pStr[0]))
pStr = pStr + "-way";
else
{
pStr = pStr + '-';
pStr = rotate(pStr);
len = pStr.length();
foundVowel = false;
for ( int counter = 1; counter < len - 1; counter++)
{
if (isVowel(pStr[0]))
{
foundVowel = true;
break;
}
else
pStr = rotate(pStr);
if (!foundVowel)
pStr = pStr.substr(1, len) + "-way";
else
pStr = pStr + "ay";
}
return pStr;
}
}
string newstring(string sentence)
{
string newsentence, currentword;
for (int i = 0; i < sentence.length(); i++)
{
if (sentence[i]==' ')
{
pigLatinString(currentword)+" ";
currentword.clear();
}
else
{
currentword+=sentence[i];
}
}
return newsentence;
}
Your newstring prototype is wrong.
void newstring(string);
Should be
string newstring(string);
Function newstring is declared as having type void
void newstring(string);
You may not create objects of type void and send them in an output stream
cout << "The pig Latin form of " << str << " is: " << newstring(str);
Also the function has no definition because you defined another function with the same name but returning std::string
string newstring(string sentence)
^^^^^^^^^^^^^^^^^^
pigLatinString(currentword)+" ";
pigLatinString returns a string, but you don't do anything with that result.
newstring returns newsentence, but is is empty.
Maybe you should fill newsentence with what is returned from pigLatinString?
Oh, and now I notice you have two newstrings... a void and a string...

Program is ignoring input

I'm trying to write a simple brainfuck interpreter in C++. It works great so far, but it ignores the character input command (',').
The Interpreter:
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
#define SIZE 30000
void parse(const char* code);
int main(int argc, char* argv[])
{
ifstream file;
string line;
string buffer;
string filename;
cout << "Simple BrainFuck interpreter" << '\n';
cout << "Enter the name of the file to open: ";
cin >> filename;
cin.ignore();
file.open(filename.c_str());
if(!file.is_open())
{
cout << "ERROR opening file " << filename << '\n';
system("pause");
return -1;
}
while (getline(file, line)) buffer += line;
parse(buffer.c_str());
system("pause");
return 0;
}
void parse(const char* code)
{
char array[SIZE];
char* ptr = array;
char c;
int loop = 0;
unsigned int i = 0;
while(i++ < strlen(code))
{
switch(code[i])
{
case '>': ++ptr; break;
case '<': --ptr; break;
case '+': ++*ptr; break;
case '-': --*ptr; break;
case '.':
cout << *ptr;
break;
case ',':
cin >> *ptr;
break;
case '[':
if (*ptr == 0)
{
loop = 1;
while (loop > 0)
{
c = code[++i];
if (c == '[') loop ++;
else if (c == ']') loop --;
}
}
break;
case ']':
loop = 1;
while (loop > 0)
{
c = code[--i];
if (c == '[') loop --;
else if (c == ']') loop ++;
}
i --;
break;
}
}
cout << '\n';
}
The UtraSimple brainfuck code that breaks everything:
,.
Does anyone know what causes it to skip the input character?
I'd be looking at this for a start:
unsigned int i = 0;
while(i++ < strlen(code)) // increments i NOW !
{
switch(code[i]) // uses the incremented i.
The first character that will get processed there will be code[1], not code[0].
So the program ",." will first process . then \0 (end of string) hence there will be no input command , processed.
You can see this if you change the code as follows:
unsigned int i = 0;
while(i++ < strlen(code))
{
cout << "DEBUG [" << i << ":" << (int)code[i] << ":" << code[i] << "]\n";
switch(code[i])
and you'll see:
DEBUG [1:46:.]
DEBUG [2:0: ]
You need to hold off on incrementing i until after you're finished with it.