Getting string length for morse code convertor keeps looping - c++

working on one of my first programming assignments, a text to morse (and back) convertor, but for whatever reason when I introduce a piece of text with a space between words my programme goes into an endless loop and crashes. Any ideas? Sorry if this description sucks, still getting my head around programming lingo.
this is the piece of the program that isn't functioning properly:
{
string user_input;
cout << "----------------------------------------" <<endl
<< "Text to Morse Mode" << endl
<< "Enter text for conversion : "<<endl;
cin >> user_input;
cout << endl << endl << user_input << " converts to : ";
unsigned int str_lenght;
str_lenght=user_input.size();
cout << endl;
for (i=0;i<str_lenght;i++)
{
find_string=0;
while (find_string < stop_string)
{
if (user_input[i]==text[find_string][0])
{
count=1;
cout << morse[find_string] << " ";
break;
}
find_string = find_string+1;
}
}
cout << endl << endl << endl;
if (count==0)
cout << endl << " an error was encountered " << "\a" << endl ;
}

stop_string isn't defined anywhere from what I see. In order to break the loop via incrementing you need to define stop_string. Also find_string = find_string+1; could be shortened to find_string++

First you haven't defined stop_string variable anywhere. First define it or use another variable. If it is string length intent to use here, use the str_length you have created.
Secondly if you want to input spaces in between your words, use getline instead of cin. cin delimits space character.

Related

I am making a quiz-like program. I already wrote the string answer ="George Washington". but when the user inputted the answer, it's wrong

answer = "George";
cout << "\t\t\t\t\t Who was the first President of United States?" << endl;
cout << "";
cout << "";
cout << "Congrats " << player1_name << " (Player1). Now, type in your answer:";
cin >> player1_answer;
if (player1_answer == answer){
cout << "check";
}else{
cout << "x";
}
This is my code. But when the user inputted the answer as exactly as what was written in the answer variable, it outputs 'x'. But if the user inputted the same answer excluding the space between "George" and "Washington", it outputs 'check'. What should I do so that the program will accept the space in the answer inputted by the user?
I tried searching the web but I can't understand a thing. So please help me
You can simply use getline instead of cin. cin reads the user input up until the first whitespace character (most commonly newlines or spaces), but getline will read user input until they hit enter. Because of this, if you want to get user input that includes spaces, you should use getline (or something similar) instead of cin.
Instead of
cin >> player1_answer;
you should use
getline(cin, player1_answer);
By using getline, the full user input ("George Washington") get assigned to the variable player1_answer. With cin, only "George" was being used, because it stopped listening for input after the first space.
Here is a full, working code example:
#include <iostream>
using namespace std;
string answer = "George Washington";
string player1_name = "Steve";
string player1_answer;
cout << "\t\t\t\t\t Who was the first President of United States?" << endl;
cout << "";
cout << "";
cout << "Congrats " << player1_name << " (Player1). Now, type in your answer:";
getline(cin, player1_answer); //Enter "George Washington"
if (player1_answer == answer){
cout << "check";
}else{
cout << "x";
}
//"check"
return -1;

C++ reset cin and cout

Ok so I have 3 functions that all represent a question that I need to answer. My first question is working with cin and cout, and is broken into parts. The problem is that after one part finishes, another part automatically takes the remainder of the input in the first part rather than asking for a new input.
My problems lay in
//part B
char state[30];
cout << "Enter a sentence: " << endl;
cin.read(state, 15);
cout << "The sentence entered was:\n";
cout.write(state, cin.gcount());
cout << endl;
and
//part E
char charArray[12]; //creates an array of 12
cout << "Enter some characters: " << endl;
cin.getline(charArray, 12, 'y');
cout << "Your characters are: " << charArray << endl;
Where whatever I enter in part b gets used in part e. I have tried using clear, ignore, and flush but to no avail. Also, the original input gets used in my other functions, as well.
My main is set up like this:
int main()
{
question1();
question2();
question3();
}
How am I able to enter a fresh input to use in each part and each function?

How come the first letter in my final cout gets cut off?

int main () {
const int MAX_INPUT = 99;
string names[MAX_INPUT];
string eraseName;
string newList;
int numNames = 0;
int i = 0;
cout << "How many names do you want (max 99)? ";
cin >> numNames;
do {
if(numNames > MAX_INPUT) {
cout << "Out of memory!" << endl;
break;
}
cout << "Enter name #" << (i+1) << ": ";
cin.ignore();
getline(cin,names[i]);
++i;
}
while (i < numNames);
cout << "What name do you want to eliminate? ";
getline(cin,eraseName);
cout << "Here is the list in reverse order, skipping ";
cout << eraseName << "..." << endl;
i = 0;
for (i = 0; i < numNames; ++i) {
cout << names[i] << endl;
}
return 0;
}
I have an assignment where I have to "eliminate" an element in an array and recreate the output. I know my final for loop will not erase the element, it's just there because I was testing the issue, but if names has two inputs (John Doe and Jane Doe) and I say to cout them the final loop couts:
John Doe
ane Doe
Move cin.ignore() right after cin >> numNames;, before the loop that reads the names.
You only need this to ignore the newline that is left in the stream after reading the number of names. getline() reads (and ignores) the newline from the stream, so there's no need to call ignore() again before reading each name. As a result, it's reading and ignoring the first character of the name.
The following block of code
if(numNames > MAX_INPUT) {
cout << "Out of memory!" << endl;
break;
}
does not need to be executed in every iteration of the do-while loop. You can change you function to use:
if(numNames > MAX_INPUT) {
cout << "Out of memory!" << endl;
// Deal with the problem. Exit??
}
do {
cout << "Enter name #" << (i+1) << ": ";
cin.ignore();
getline(cin,names[i]);
++i;
} while (i < numNames);
Once you move the check out of the loop, you have to ask yourself, "Do I need to ignore a character in each iteration of the loop?" The answer is "No". You need to ignore the newline only after reading numNames. So, you move it out of the loop also.
if(numNames > MAX_INPUT) {
cout << "Out of memory!" << endl;
// Deal with the problem. Exit??
}
// Ignore the newline left on the stream before reading names.
cin.ignore();
do {
cout << "Enter name #" << (i+1) << ": ";
getline(cin,names[i]);
++i;
} while (i < numNames);
You can improve on that by making sure that everything up to and including the newline is ignored by using:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Add
#include <limits>
to be able to use std::numeric_limits.

I am trying to use a do while loop to repeat a certain portion of my program and it refuses to execute properly

Okay so as the title said its refusing to execute the stuff right under the "do" function even though as far as i can tell all the parameters for a repeat have been fulfilled. So far what i get when i run the program is something along the lines of...
"Would you like to search another name?
Please enter Y for yes and n for no:"
looping over and over when i press y
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, sID, sClass, sSearch, cQuestion;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << endl;
}
cout << "\n";
// Search function
do
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
} while (cQuestion == "Y" || cQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
Edit:
Posted whole program, please excuse any grammatical mistakes, I'm just trying to get the program down before i go in there and make it pretty.
The tail of your loop does this:
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
which will consume your string if you entered one, but leave the trailing newline in the input stream. Thus when you return to the top of the loop after entering Y or y, and do this:
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
the getline will extract an empty line.
How to consume the unread newline from the input stream is up to you. You will likely just end up using .ignore() as you did prior in your program. Or use getline to consume cQuestion. You have options. Pick one that works.
And as a side note, I would strongly advise you check your stream operations for success before assuming they "just worked". That is a hard, but necessary, habit to break. Something like this:
do
{
cout << "Please Enter a name to be searched:" << endl;
if (!getline(cin, sSearch))
break;
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
} while (getline(cin,cQuestion) && (cQuestion == "Y" || cQuestion == "y"));
If cQuestion is a char array then you need to use strcmp or stricmp to compare it with another string i.e. "Y" and "y" in this case. If cQuestion is a single char then you need to compare with 'Y' and 'y' (i.e. with a single quote)
Strings in C++ are not first class types therefore they do not have some of the string operation that exist for other basic types like ints and floats. You do have std::string as part of the standard C++ library which almost fulfills the void.
If you just change the type of cQuestion to std::string your code should work but if you want to stick with chars then you will need to change the quote style.

Check for non-numeric inputs in a C++ program

How do you check for non-numeric input using C++? I am using cin to read in a float value, and I want to check if non-numerical input is entered via stdin. I have tried to use scanf using the %d designator, but my output was corrupted. When using cin, I get the correct format, but when I enter, a string such as "dsffsw", I get an infinite loop.
The commented code was my attempt to capture the float, and type cast it as string, and check if it is a valid float, but the check always comes up false.
I have tried using other methods I have found on the message boards, but they want to use scanf in C and not cin in C++. How do you do this in C++? Or in C if it is not feasible.
while (!flag) {
cout << "Enter amount:" << endl;
cin >> amount;
cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl;
//if (!strtod(((const char *)&amount), NULL)) {
// cout << "This is not a float!" << endl;
// cout << "i = " << strtod(((const char *)&amount), NULL) << endl;
// //amount = 0.0;
//}
change = (int) ceil(amount * 100);
cout << "change = " << change << endl;
cout << "100s= " << change/100 << endl;
change %= 100;
cout << "25s= " << change/25 << endl;
change %= 25;
cout << "10s= " << change/10 << endl;
change %= 10;
cout << "5s= " << change/5 << endl;
change %= 5;
cout << "1s= " << change << endl;
cout << "END The amount you entered is: " << amount << endl;
}
return 0;
}
int amount;
cout << "Enter amount:" << endl;
while(!(cin >> amount)) {
string garbage;
cin.clear();
getline(cin,garbage);
cout << "Invalid amount. "
<< "Enter Numeric value for amount:" << endl;
}
I think you task relates to the so called defensive programming, one of it`s ideas is to prevent situations like one you described (function expects one type and user enters another).
I offer you to judge whether input is correct using method that returns stream state , which is good(),
so I think it will look something like this:
int amount = 0;
while (cin.good()) {
cout << "Enter amount:" << endl;
cin >> amount;