Trouble with morse code spaces between words - c++

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

Related

Find a word in a sentence c++

This code should say if a word is present in a sentence or not. When I insert the sentence and the word where I declare the strings(for exemple: string s = "the cat is on the table" string p = "table" the program says that the word is in the sentence) the code works but, with the getline, the for cycle never begin and it always says that the word isn't in the sentence.
Please help I dont know what to do
#include <iostream>
#include <string>
using namespace std;
int main () {
string s;
string p;
string word;
bool found = false;
int sl = s.length();
int beg = 0;
int pl = p.length();
cout << "sentence: ";
getline(cin, s);
cout << "word: ";
getline(cin, p);
for(int a = 0; a<sl; a++)
{
if(s[a]== ' ')
{
word = s.substr(beg, a-beg);
if (word== p)
{
found = true;
break;
}
beg = a+1;
}
}
if (found== true)
{
cout <<"word " << p << " is in a sentence " << s;
}
else
{
word = s.substr(beg);
if (word== p)
{
found = true;
}
if(found == true)
{
cout <<"the word " << p << " is in the sentence " << s;
}
else
{
cout <<"the word " << p << " isn't in the sentence " << s;
}
}
}
after taking the input strings then use length() to find the length, otherwise you are not taking the actual size of the strings.
getline(cin, s);
getline(cin, p);
int sl = s.length();
int pl = p.length();
For splitting the words after taking the input string by getline() you can use stringstream which is a builtin c++ function, like :
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string arr;
getline(cin, arr);
stringstream ss(arr);
string word;
while(ss >> word){
// your desired strings are in `word` one by one
cout << word << "\n";
}
}
Another thing is that you can declare the strings like string s, p, word;

I want to remove occurrences of a given letter

I have attempted to remove the occurrences of a user inputted letter after they've chosen a word however, the final output prints out a random string of letters and numbers instead of what I expected. For example, if the user enters the text "Coffee" then proceeds to enter the letter "f", the program should return "Coee" as the final print. However, this is not the case. Could anyone check to see where I've gone wrong? Much obliged.
#include <iostream>
#include <string>
using namespace std;
void removeAllOccurrence(char text[], char letter)
{
int off;
int i;
i = off = 0;
if (text[i] == letter)
{
off++;
}
text[i] = text[i + off];
}
int main() {
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " << removeAllOccurrence << endl;
system("pause");
return 0;
}
This should do the job
#include <algorithm>
#include <string>
#include <iostream>
void remove_char(std::string s, char r) {
s.erase( std::remove( s.begin(), s.end(), r), s.end()) ;
std::cout << s << std::endl;
}
int main()
{
std::string test = "coffee";
char r = 'f';
remove_char(test, r);
return 0;
}
If u want to do this by hand try this:
std::string removeAllOccurrence(string text, char letter)
{
int off;
int i;
i = off = 0;
string out = "";
for (i = 0; i < text.size(); i++)
{
if (text[i] != letter)
{
out += text[i];
}
}
return out;
}
int main(void)
{
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " + removeAllOccurrence(text, letter) << endl;
system("pause");
return 0;
}
As you can see your main function was kinda right. You just need to pass some arguments into the function. Additonally you missed a loop in your remove function. If you use string in your main, why don't use string in yur function? You can just use string there, too
Kind Regards

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;
}

C++ - Replacing "_" with a character

Using C++, I'm trying to make a hangman game to become better at using C++ and programming in general. Anyways, the issue I'm facing is that I'm not sure how to replace the dashes within a string with the letter the user has guessed.
I think my problem is with the fact the word chosen is randomly chosen from an array and I'm not sure how to go about finding the positions within the randomly chosen string which consists of the guessed character.
I have commented out the area that's causing the issue.
#include <iostream>
#include <array>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <cstddef>
#include <algorithm>
using namespace std;
int main()
{
string words[3] = {"stack", "visual", "windows"};
string guess;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 1; i <= selected.size(); i++) {
cout << "_ ";
}
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
if (selected.find(guess) != string::npos) {
/*for (int i = 1; i <= selected.size(); i++) {
if (selected.find(guess) != string::npos) {
cout << "_ ";
} else {
cout << guess << " ";
}
}*/
} else {
cout << "\nNay!\n";
cout << "\n";
}
cout << "\n";
cout << "\n";
system("PAUSE");
return 0;
}
I was thinking about using the replace() function but the problem I face here is that I'm not replacing the string within selected variable but sort of iterating through the word itself, if that made any sense whatsoever?
Use a second string, that is initialized with the underscores. If the find function doesn't return string::npos it returns the position in the string, and this is the same position you should change in the string with the underscores as well.
You actually need to use a second string to store the "guessed" string; this is because you need to keep track of all the guessed letters and display them.
something like :
string s ="test";
string t=""; //empty string
for(int i=0;i<s.size();i++)
t.append("_"); //initialize the guess string
cout<<t<<'\n';
char c;
cin >> c;
int pos = s.find(c); //get the first occurrence of the entered char
while(pos!=-1) //look for all occurrences and replaced them in the guess string
{
t.replace(pos,1,1,c);
pos = s.find(c, pos+1);
}
I think you need to maintain some extra state while looping - to keep track of which letters have / haven't been guessed.
You could add a new string current_state which is initially set to the same length as the word but all underscores. Then, when the player guesses a letter, you find all instances of that letter in the original word, and replace the underscore with the letter guessed, at all the positions found but in current_state.
First i would initialize a new string to show the hidden word:
string stringToDisplay = string( selected.length(), '_');
Then For each letter given by the user i would loop like this:
(assuming guess is letter)
size_t searchInitPos = 0;
size_t found = selected.find(guess, searchInitPos));
if (found == string::npos)
{
cout << "\nNay!\n";
cout << "\n";
}
while( found != string::npos)
{
stringToDisplay[found] = guess;
searchInitPos = found+1;
found = selected.find(guess, searchInitPos));
}
cout << stringToDisplay;
Hope this will help
I think it should be that:
string words[3] = {"stack", "visual", "windows"};
char guess;
string display;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 0; i < selected.size(); i++) {
display.insert(0, "_ ");
}
cout << display;
while(display.find("_ ") != string::npos) {
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
bool flag = false;
for (int i = 0; i < selected.size(); i++) {
if (selected[i] == guess) {
display.replace(i*2, 1, 1, guess);
flag = true;
}
}
if (!flag) {
cout << "\nNay!\n";
cout << "\n";
} else {
cout << display;
}
}

Can't figure out how to print sequences of letters in C++

I am working on a project where I will be able to read in a file that contains any text, like the sample text below. Then, character by character, it will be able to output n-character long sequences (represented below as a read-in value given by the user along the lines of 1, 2, 3, 4...) along the whole length of the text. So, for example:
As Gregor Samsa awoke one morning from uneasy dreams he found himself transformed in his bed into a gigantic insect.
If the user provided 2 as the sequence length, the program should spit out: "As" "s " " G" "Gr" "re" "eg" "go" "or" "r " and so on...
I have written this code but don't know why it won't work. Right now, it doesn't spit out every possible variation of the sequence. Any suggestions would be very helpful. Thanks.
#include "genlib.h"
#include <iostream>
#include <fstream>
#include "simpio.h"
#include "random.h"
#include "vector.h"
#include "map.h"
/* Private Instance Variables */
int seed_length;
string line;
string seed_string;
string next_string;
char ch;
/* Function Prototypes */
string promptUserForFile(ifstream & infile);
int main() {
ifstream infile;
promptUserForFile(infile);
// Ask what order of Markov model to use.
cout << "What order of Markov model should we use? ";
cin >> seed_length;
while (infile.eof() == false) {
ch = infile.get();
for (int i = 0; i < seed_length - 1; i++) {
cout << "ch up here is " << ch << endl;
if (isspace(ch) && i == 0) {
seed_string += ch;
} else {
seed_string += ch;
ch = infile.get();
}
}
next_string = ch;
if (isspace(ch)) {
next_string = " ";
} else {
char trythis = infile.get();
next_string += trythis;
}
cout << seed_string << endl;
cout << next_string << endl;
seed_string = "";
next_string = "";
}
cout << "TEST" << endl;
// Close the file when you're done storing all of the scores.
infile.close();
return 0;
}
string promptUserForFile(ifstream & infile) {
string prompt = "Please input your filename: ";
while(true) {
cout << prompt;
string filename;
getline (cin, filename);
infile.open(filename.c_str());
if(!infile.fail()) return filename;
infile.clear();
cout << "Unable to open that file. Try again." << endl;
if (prompt == "") prompt == "Input file: ";
}
return 0;
}
The code has two problems.
The special handling for isspace is broken:
if (isspace(ch) && i == 0) {
seed_string += ch;
} else {
seed_string += ch;
ch = infile.get();
}
This essentially means that if the first character in this loop is a space, it will be added twice.
Every character received from infile.get() is only added to seed_string once (with the exception of isspace characters).
A better way to code this is to recognize that:
You have to ignore consecutive isspace characters.
Every sequence can be obtained by removing the first character of the preceding sequnce and appending the next character from the file.
Here is a better implementation; it takes the order of the Markov model in the first command line parameter and takes the text from standard input. By encapsulating the skipping of duplicate spaces in a separate function, you don't have to deal with it in the main body of the algorithm.
#include <iostream>
#include <cstdlib>
char next_character() {
static bool was_space = false;
char ret = 0;
do {
ret = std::cin.get();
} while (was_space && std::isspace(ret));
if (std::isspace(ret)) {
was_space = true;
ret = ' ';
} else {
was_space = false;
}
return ret;
}
int main(int argc, char **argv) {
if (argc != 2) return 0;
int mlen = std::atoi(argv[1]);
std::string seq;
for (unsigned i = 0; i < mlen; ++i) {
seq += next_character();
}
std::cout << seq << '\n';
while (true) {
seq.erase(0, 1);
char c = next_character();
if (std::cin.eof()) break;
seq += c;
std::cout << seq << '\n';
}
return 0;
}
Example input:
This is a test
Example output:
This
his i
is is
s is
is a
is a
s a t
a te
a tes
test