C++ If Else statement Problems - c++

My code contains an If Else statement. I want it to validate a string that a user inputs puts into the script on two things:
The length of the string has to be more than 0
The string has to consist of alphabet characters
Below is my code, I think the error is to do with the length of the string piece of code.
Before Edit:
cout << "Your word: " << szOriginal << "\n";
if szOriginal.length() > 0 and (isalpha(szOriginal))
{
szWord = szOriginal.tolower();
cout << szWord << "\n";
}
else
{
cout << "Please enter a valid word." << endl;
}
Sorry guys, the error produced by Dev-C++ is
expected '(' before "szOriginal"
Link to printscreen: http://gyazo.com/b3f43928072e9c2a5a8a712a9030364d
After Edit with variable declaration and such:
#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
string original;
cout << "Welcome to the English to Pig Latin translator!\n";
cout << "Type a word you wish to translate:\n";
cin >> original;
cout << "Your word: " << original << "\n";
if (original.length() > 0 && (isalpha(original)) )
{
word = original.tolower();
cout << Word << "\n";
}
else
{
cout << "Please enter a valid word." << endl;
}
system("PAUSE");
return 0;
}
So sorry for this bad post!

if ( [...] ) - you're missing the brackets.
Also, it's && instead of and.

I think you are coming from a python background
cout << "Your word: " << szOriginal << "\n";
if (szOriginal.length() > 0 && (isalpha(szOriginal)) )
{
szWord = szOriginal.tolower();
cout << szWord << "\n";
}
else
{
cout << "Please enter a valid word." << endl;
}
you need ( ) around the if condition, and use && for logical and
EDIT
you are using szOriginal as a char when you say isalpha(szOriginal)
and as an object when you say szWord = szOriginal.tolower();
so you need to look into that also

Related

Is there a way to use bools with strings? I want to search for a word in a string, and if it's there, output the meaning

I am very new to coding and this is my first language, C++. I have an assignment that is really confusing.
The assignment wants me to search the user input of one line for slang words. Ex: TMI or BFF. However, I don't know how to use conditional expressions to do this, and I have tried if-else statements but they end up reading all the statements instead of each one that applies. The code always comes up with a problem for the conditional expression because I honestly have no clue how to use them for strings in this manner. Any help is appreciated!
(Slang terms are required to be capitalized to be read.)
#include <iostream>
#include <cctype>
#include <iomanip>
#include <string>
using namespace std;
int main() {
string userInput;
int textSlang = '0';
cout << "Welcome to the Text Message Decoder!" << endl;
cout << "WARNING! Slang is case-sensitive. Please make sure all slang is fully capitalized!" << endl;
cout << "Enter a single line text message: " << endl;
getline(cin, userInput);
cout << "You entered: " << userInput << endl;
if (textSlang == string::npos) {
cout << "Error" << endl;
}
else if ((textSlang = userInput.find("IDK" ))) {
cout << "IDK: I don't know" << endl;
}
else if ((textSlang = userInput.find("TTYL" ))) {
cout << "TTYL: Talk to you later" << endl;
}
else if ((textSlang = userInput.find("TMI" ))) {
cout << "TMI: Too much information" << endl;
}
else if ((textSlang = userInput.find("JK" ))) {
cout << "JK: Just kidding" << endl;
}
else if ((textSlang = userInput.find("BFF" ))) {
cout << "BFF: Best friends forever" << endl;
}
else if ((textSlang = userInput.find("LOL" ))) {
cout << "LOL: Laugh out loud" << endl;
}
else if ((textSlang = userInput.find("TYSM" ))) {
cout << "TYSM: Thank you so much" << endl;
}
else if ((textSlang = userInput.find("OMG" ))) {
cout << "OMG: Oh my god" << endl;
}
cout << "END." << endl;
//textSlang = userInput.find("TTYL");
//textSlang = userInput.find("TMI");
//textSlang = userInput.find("JK");
//textSlang = userInput.find("BFF");
//textSlang = userInput.find("LOL");
//textSlang = userInput.find("TYSM");
//textSlang = userInput.find("OMG");
}
This code:
else if ((textSlang = userInput.find("IDK" ))) {
cout << "IDK: I don't know" << endl;
}
assigns textSlang to 0 IFF userInput begins with IDK. In all other cases it assigns some value other than 0.
And all int values other that 0 evaluate to true.
You want:
else if ((textSlang = userInput.find("IDK" )) != string::npos) {
cout << "IDK: I don't know" << endl;
}

Why does program complain of too many commas?

Here is my code, I have attached the screenshot of what output Zybooks expects, and what my output is. I am trying to get it to output exactly what Zybooks is asking, however something seams to be wrong. It is compiling though. Or maybe Zybooks is just being stupid?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cstring>
using namespace std;
int main() {
string title;
string col1;
string col2;
string val;
int numCommas = 0;
vector<string> stringData;
vector<int> intData;
cout << "Enter a title for the data:" << endl;
getline(cin, title);
cout << "You entered: " << title << endl << endl;
cout << "Enter the column 1 header:" << endl;
getline(cin, col1);
cout << "You entered: " << col1 << endl << endl;
cout << "Enter the column 2 header:" << endl;
getline(cin, col2);
cout << "You entered: " << col2 << endl << endl;
while (1) {
cout << "Enter a data point (-1 to stop input):" << endl;
getline(cin, val);
if (val == "-1") {
break;
}
if (val.find(',') == -1) {
cout << "Error: No comma in string." << endl << endl;
}
else {
for (int i = 0; i < val.length(); i++) {
if (val.at(i) == ',') {
numCommas++;
if (numCommas > 1){
break;
}
}
}
if (numCommas == 1) {
stringData.push_back(val.substr(0, val.find(',')));
intData.push_back(stoi(val.substr(val.find(',') + 1, val.length() - 1)));
cout << "Data string: " << val.substr(0, val.find(',')) << endl;
cout << "Data integer: " << stoi(val.substr(val.find(',') + 1, val.length() - 1)) << endl;
}
else {
cout << "Error: Too many commas in input." << endl << endl;
}
}
}
return 0;
}
Thanks.
Thanks.
Your problem is that you initialise numCommas to zero at the start of the program rather than at the start of each author input. That means, once it exceeds one, it will stay that high at least(a), meaning future inputs will always be seen as having too many commas.
You just need to set it to zero immediately before checking each input.
(a) Well, until it wraps around (if it wraps around). But that will be an awful lot of commas you need to input :-)

C++ Cash Register Program Not using <string>

I have to write a program without using strings . Here is my code :
#include <iostream>
#include <iomanip>
using namespace std;
struct product
{
char productName[100];
double productPrice = 0;
};
const int MAX_CHAR = 101;
const int MAX_ITEM = 100;
int main()
{
product item[MAX_ITEM];
double total = 0;
int count = 0;
for (int i = 0; i < MAX_ITEM; i++)
{
cout << "Please , enter the product name(for checkout type -1) : ";
cin.get(item[i].productName, MAX_CHAR, '\n');
cin.ignore(100, '\n');
if (strcmp(item[i].productName, "-1") == 0 ) {
break;
}
else {
count++;
cout << "Please , enter the price for " << item[i].productName << " : $";
cin >> item[i].productPrice;
cin.ignore(100, '\n');
total += item[i].productPrice;
cout << endl << "Product entered : " << item[i].productName << " " << "$"
<< fixed << setprecision(2) <<item[i].productPrice << endl;
cout << "Total : $" << total << endl << endl;
}
}
cout << endl << "###############";
cout << endl << "Your Receipt : " << endl << endl;
for (int i = 0; i < count; i++) {
cout << item[i].productName << " $" << fixed << setprecision(2) << item[i].productPrice << endl;
}
cout << endl << "Total : $" << total;
cout << endl << "###############";
getchar();
getchar();
return 0;
}
I have a couple questions :
Why does the program crash if I don't use cin.ignore(100, '\n'); after cin >> item[i].productPrice; ? It's just cin without any condition, so it should not leave a new line char in input stream?
How can I check if the price doesn't contain incorrect input (so it has only decimal or floating point numbers) ?
How can I check if the name contains chars and numbers which are >0 (except -1) ?
Is it better to use cin.getline in this case ?
cin is an istream, so it should leave the newline char in the stream if you use cin.get(). I haven't tested if this is the cause of your crash but it sounds like this could give you problems.
chars are just numbers. A . is 46, the digit characters are from 48 through 57. You could read your price input into a buffer and check if you read any char that does not have one of your desired values. If you find an unwanted char, you can decide if you want to repeat the input, ignore this item or exit the program.
In your else branch, check if the first character of productName is a '-'. That way, you already ensured that productName is not -1.
cin.getline() discards the newline character, so you could avoid the use of cin.ignore().

While loops expression

I'm trying to write a program that asks the user to enter digits between 0 and 1000000 and it outputs the occurrence of a certain number (that the user entered as well)
I've wrote this program and I believe it works well, but I have one issue which is if the while expression is not true, I want to cout a certain message but I don't know where to place it.
Here's my program:
#include <iostream>
using namespace std;
int main()
{
int n,j=0,key;
cout << "Pleaser enter digits\n";
cin >> n;
cout << "please enter key number\n";
cin >> key;
while (n>0 && n<1000000)
{
if(n%10==key)j++;
n= n/10;
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
Thanks in advance!
Use
if(n>0 && n<1000000)
{
while(n)
{
if(n%10==key)
j++;
n= n/10;
}
}
else
cout<<"n is supposed to be between 0 and 1000000";
As there are no breaks (or no other piece of code that can jump) inside the bucle, everything after the while structure is executed because the expression returned false.
while (n>0 && n<1000000)
{
if(n%10==key)j++;
n= n/10;
}
cout << "While expression not anymore true" << endl;
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
UPDATE
Based on the comments, it seems that you want to check if the number entered is valid or not. Simply, just check it before the while:
if(not (n>0 and n<1000000)) cout << "Number must be between 0 and 1000000" << endl;
else {
while (n)
{
if(n%10==key)j++;
n= n/10;
}
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
Write a if statement before while loop.
if(!(n>0 && n<1000000))
{
cout << "....";
return -1;
}
while(..)

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.