trouble understanding if statement with strings - c++

i've started learning c++ today.
Now i think that i've got the basics, i couldn't get with this program i'm trying to execute.
Basically all program need to do is, output the user first name, and last name.
Now i got it to work, but i want that if the user input a random number, the program won't execute, and output "Only Text allowed. Please enter your name again: "
also, how do i create space between the first and last name?
would appreciate help. thanks!
this is the code:
int main()
{
int Num;
string First;
string Last;
cout << "Type in your first name please:";
cin >> First;
if (not sure what to declare here)
{
cout >> "No numbers allowed. only Text.";
}
cout << "Type your last name please:";
cin >> Last;
cout << "your full name is:" << " " << First + Last;
}

You will need to search the string for digits.
Here is one method to find numeric digits in a string. There are many others.
static const char digits[] = "0123456789".
if (First.find_first_of(digits) != std::string::npos)
{
cout << "First name has at least one digit.\n";
}
Edit 1:
If that is not easily understood, here is a more basic version:
const unsigned int length = First.length();
for (unsigned int i = 0; i < length; ++i)
{
const char c = First[i];
if (std::isdigit(c))
{
std::cout << "Name has a digit, at position " << i << "\n";
break;
}
}

Related

How to check if char doesnt exist in a string

Say we have the user input a name that is a string "william" and then the user enters the character that they want to find the index of.
using namespace std;
string name;
char characterToFind;
cout << "Enter a name ";
cin >> name;
cout << "Enter a character to find ";
cin >> characterToFind;
We then want to find the index of the character in the name string array.
for (int j = 0; j < name.length(); j++) {
if (name[j] == characterToFind) {
cout << "char is at index: " << j << endl;
}
}
How do I then check if the inputted character doesnt exist in the name string array? I try to do the following:
if (characterToFind != name.find(characterToFind)) {
cout<< "doesnt exist" << endl;
}
The if statement always seems to be true and runs the code even if the character that was inputted existed in the name string array.
The problem with my approach was that I was doing was that in the if condition i was checking a 's' char vs a index position of an array.
instead, doing:
if (name.find(characterToFind) == std::string::npos) {
cout << "doesnt exist" << endl;
}
this is checking if the character input is equal to a position that doesnt exist! This is true so it tells the user that the character entered does not exist.

How to add numbers bigger than long long, long, int and etc C+11

forum!
I have a project where we are supposed to add numbers that are length 14 or greater. I did some digging and realized that there is no current type that takes numbers this big. So, I have the user enter the numbers as a string and the numbers they would like to add are stored in a static string array.
I would like to add the numbers from the static array together. The issue is I have no idea how to deal with numbers this large. I am assuming you would have to convert the string values into int's and add them up one by one? I am having a big issue coming up with the logic for this. Any help would be appreciated.
If not, if you can provide some context which could help me come up with some logic.
The only library functions I can use is iostream and string.
Here is my code if you'll like to see my logic! I have some test cases I am trying to figure out so please ignore the comment outs. But, if you run the code you should get a better sense of what I am trying to get out. I am trying to sum up the numbers the user enters.
#include <iostream>
#include <string>
using namespace std;
void amountOfNumbers(string &userAmount, int MIN_AMOUNT, int MAX_AMOUNT){
//string alpha = "abcdefghijklmnopqrstuvwxyz";
cout << "How many numbers? -> ";
cin >> userAmount;
cout << endl;
while(!userAmount.find("abcdefghijklmnopqrstuvwxyz")){
cout << "ERROR: must be a number, try again ->";
cout << userAmount;
//cin.clear();
//cin.ignore(1000, '\n');
cin >> userAmount;
cout << endl;
}
int temp = stoi(userAmount);
while((temp < MIN_AMOUNT) or (temp > MAX_AMOUNT)){
cout << "ERROR: Program can only take in " << MIN_AMOUNT << " - "<< MAX_AMOUNT << " numbers. Try again ->";
cin >> userAmount;
cout << endl;
temp = stoi(userAmount);
}
}
void takeNumbers(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << "Input number #" << i+1 << " ->";
cin >> numberArray[i];
cout << endl;
}
}
void display(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << numberArray[i];
cout << endl;
}
}
void addNumber(string &userAmount, string (&numberArray)[11]){
}
int main() {
const int MIN_AMOUNT = 2, MAX_AMOUNT = 11, MAX_INPUT = 14;
string userAmount = "0";
string numberInput;
// static array
string numberArray [MAX_AMOUNT];
amountOfNumbers(userAmount, MIN_AMOUNT, MAX_AMOUNT);
takeNumbers(userAmount, numberArray);
display(userAmount, numberArray);
}

Can't compare string with while and if statements

I'm trying to create a command menu where the user will be able to perform as many commands as he/she wants until pressing "q" which will end the loop. I think I have everything I need to do this except I realized mid-way that my professor asked to use string. When I included string into the program, I began to get error messages saying "could not convert string to bool" wherever there was a while or if statement. What can I do to fix this problem and get my program working. Thanks in advance.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char option;
char number=0;
string s;
string n;
string p;
string q;
char number2;
cout << " Please enter a number: "<< endl;
cin >> number;
do {
cout << " Please enter a command: " << endl;
cout << " s- square the number " << endl;
cout << " n- add the number and (number +1) " << endl;
cout << " p- add the number and (number -1) " << endl;
cout << " q- quit" << endl;
cin >> option;
if (option=s) {
s= number*number;
cout << "Square of this number is : " << s;
}
else if ( option=n){
number2= number+1;
n= number+number2;
cout << "Sum of" << number << "+" << number2 << "is: " << n;
}
else if (option=p) {
number2= number-1;
p= number+number2;
cout << "Sum of" << number << "+" << number2 << "is" << p;
}
else if (option=q)
cout << "Terminating Program";
} while(option);
return 0;
}
you're assigning in the if and else if rather than comparing.
if (option=s) {
should be
if (option=='s') {
note the double =
Also, you need to put single quotes (') around the character choice.
It's a common mistake that even experienced developers make.
These declarations
char number=0;
string s;
string n;
string p;
string q;
char number2;
should all be int
int number=0;
int s;
int n;
int p;
int q;
int number2;
Let me answer as if I were who will evaluate your homework. You have several issues here:
You are asked to use string. Avoid the use of char and string together.
char option; // professor asked to use string: (-1) point
string option; // ok
When you use a single =, like in option="a", you are assigning the value "a" to the variable option. But in the if-else statements you want to compare, so you should use the == comparison operator. Also, you can't compare a char with a string.
if(option = "a") // error: expression must have bool type: (-2) points
if(option == 'a') // error: no operator "==" matches std::string == char; (-2) points
if(option == "a") // ok
You use while(option), but option is declared as a char, not as a bool. Replace this line to while(option!="q") to finish when you enter q.
while(option); // error: expression must have bool type; (-2) points
while(option != "q"); // GOOD!
Also, your program will finish when you scape from the while-statement; so, try to put the "Terminating Program" message after this.
You do not need to declare such many variables (s, n, p, q, number2). Try to use temporary variables inside each scope, for example:
if (option=="s")
{
cout << "Square of this number is : " << number*number << endl;
}
else if ( option=="n")
{
int number2= number+1;
cout << "Sum of " << number << "+" << number2 << " is : " << number+number2 << endl;
}
In the form you write this code, every time you type a new option you will obtain an output like:
Sum of 10+11 is : 21 Please enter a command:
This is ugly to me (-1 point). Try to put a newline (<< endl;) after every cout lines.
Finally, what if I type any other letter not listed in the menu? I would expect a message like Enter a valid option (-1 point).

Error: Must have class type

I need to create a list of contacts and I keep getting this error in my code: expression must have class type.
Here's the code:
#include<iostream>
#include<string>
using namespace std;
class PhoneApp {
public:
string FirstName;
string LastName;
string PhoneNumber;
string EmailID;
PhoneApp() {
FirstName = "";
LastName = "";
PhoneNumber = "";
EmailID = "";
}
void addContact(){
cout << "Enter your contact's first name: ";
cin >> FirstName;
cout << "Enter your contact's last name: ";
cin >> LastName;
cout << "Enter your contact's phone number: ";
cin >> PhoneNumber;
cout << "Enter your contact's email address: ";
cin >> EmailID;
}
void displayContact(){
cout << "Here's your contact details: " << endl;
cout << "FirstName: " << FirstName << endl;
cout << "LastName: " << LastName << endl;
cout << "PhoneNumber: " << PhoneNumber << endl;
cout << "EmailID: " << EmailID << endl;
}
};
int main(){
PhoneApp myPhoneApp[50];
int index = 0;
while(1){
cout << "Press 1 to add contacts" << endl;
cout << "Press 2 to search for a contact" << endl;
cout << "Anything else to quit" << endl;
int choice;
cin >> choice;
switch(choice){
case 1:{ myPhoneApp[index].addContact();
index++;
break;}
case 2: { cout << "Enter a first name to search for: " << endl;
string search = "";
cin >> search;
for (int i = 0; i < index; i++) {
if(myPhoneApp[50].FirstName[i].compare(index) == 0);
break;
}
}
default: exit(1);
}
}
system("pause");
return 0;
}
The error pops up at
if(myPhoneApp[50].FirstName[i].compare(index) == 0
What exactly is the problem here and how do I fix it?
Thanks for the help
There are multiple errors in your code, but the one that you are pointing to is as follows:
myPhoneApp[50].FirstName is a string
Strings consist of characters. You access characters in a string using a subscript operator [i]
Characters are primitives.
You can access members using a dot . on classes and structures, but not on primitives
Since myPhoneApp[50].FirstName[i] is a char, and since char is a primitive, using a dot on it is invalid.
cout << "Enter a first name to search for: " << endl;
string search = "";
cin >> search;
for (int i = 0; i < index; i++) {
if(myPhoneApp[i].FirstName.compare(search) == 0) {
//do stuff
break;
}
}
Several things were going wrong.
First off, you need to compare the entire FirstName string to search, not individual characters of FirstName.
Second, you need to iterate through the contacts in myPhoneApp[], not just keep checking different characters of the FirstName string in index 50, which isn't even necessarily set.
Third, no string.compare() overloads take a single int as an argument. What you're looking for is the method to compare two strings, which is what my answer will do.
Fourth, an issue you didn't get to yet... you had a semicolon after your if statement, so regardless of the condition of the if statement, nothing really executes... and you'd just hit that break; after a single iteration, no matter what.
dashblinkenlight's answer explains why the error message was what it was, mine shows you how to fix your program.
There are several small things coming together here to cause you a problem.
if(myPhoneApp[50].FirstName[i].compare(index) == 0);
break;
Firstly: You have a stray semicolon on the end of the "if" line
if();
means "do the test, and then forget about it. always do the thing on the next line".
Secondly, you are only ever checking one element of your contacts list
myPhoneApp[50]
surely you mean't
myPhoneApp[i]
Next, myPhoneApp[50].Firstname resolves to a single instance of std::string, you then try to index the letters in that name and compare them with the number of entries in your index.
myPhoneApp[50].FirstName[i].compare(index)
What you presumably mean is
if(myPhoneApp[i].FirstName == search)
break;
---- Edit ----
You've given your member variables of "myPhoneApp" upper-camelcase names, just like your class names. This is going to confuse you, and it means you can't name your member variables to match their type:
PhoneApp PhoneApp;
is a compile error.
A common practice is to give member variables distinctive names by adding a prefix ("m_" for member) or suffix (some places add "_" to indicate a member variable).
E.g.
class PhoneApp {
public:
string m_FirstName;
string m_LastName;
string m_PhoneNumber;
string m_EmailID;
PhoneApp() {
m_FirstName = "";
m_LastName = "";
m_PhoneNumber = "";
m_EmailID = "";
}
};
or "m_firstName", "m_lastName" etc.

Beginner's C++ program for a class

the assignment is the basic "cin a full name" and then "retrieve First Middle Last" bit, where you create a program that asks the user to type in their full first name into a single string and the programs picks apart the name and outputs it organized seperately. this is what i wrote:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int index;
index = name.find(' ');
cin >> name;
cout << "First name: " << name.substr(0, index) << endl;
name = name.substr(index+1, name.length()-1);
index = name.find(' ');
cout << "Middle Name: " << name.substr(1, index) << endl;
name = name.substr(index+1, name.length()-1);
cout << "Last name: " << name;
return 0;
}
the code just wont seperate them right, and will not redefine 'name' correctly.
It always just bounces back to the beginning of the string.
any help for a newbie?
here's an example output:
Teenage Wonder Land
First name: Teenage
Middle Name: eenag
Last name: Teena
Process returned 0 (0x0) execution time : 7.942 s
Press any key to continue.
You wont' find anything before type your in console and sbustr should read from index 0
string name;
int index;
//index = name.find(' '); // comment out, name is empty, you won't find anything
cin >> name;
index = name.find(' '); // now you can find first space
cout << "Middle Name: " << name.substr(0, index) << endl;
// ^
Or just use std::stringstream
#include <sstream>
std::stringstream ss(name);
std::string token;
int i = 0;
while(ss >> token)
{
switch(i)
{
case 0:
std::cout << "First name: " << token << std::endl;
break;
case 1:
std::cout << "Middle name: " << token << std::endl;
break;
case 2:
std::cout << "Last name: " << token << std::endl;
break;
default:
break;
i++;
}
}
You clearly can't search for something in name before you assign it a value, which is what you're doing now:
string name;
int index;
index = name.find(' '); // No value assigned to name yet - nothing to search
cin >> name; // Now you're giving it a value (too late)
Instead, assign and then try to find a value:
string name;
int index;
cin >> name; // Assign a value first
index = name.find(' '); // Now try to find something in it
I think you should use std::getline to get the entire line of text at once. Currently you are only reading in the first word (>> operator will only extract text up to the next whitespace character).
std::string name;
if (std::getline(cin, name))
{
// extraction successful, "name" should contain entire line
}
Then, you can use one of the other answers in this question or continue with your own approach.
The extraction operator >> for istream will grab all non-whitespace characters in the buffer until it encounters a whispace.
So your input here:
Teenage Wonder Land
contains 3 whitespaces including the invisible newline at the end when you hit enter. From this you should be able to figure out what the following does:
cin >> name;
Hint: name doesn't contain the entire line you just entered.
#include <iostream>
#include <string>
using namespace std;
string getnext(const string &full, const string &delim, size_t &beg) {
size_t prev = beg;
beg = full.find(delim, beg);
if (beg != string::npos)
return full.substr(prev, beg-prev);
return full.substr(prev, full.length()-prev);
}
int main()
{
string name, temp, error = "NameError: Enter first, middle, last";
size_t index = 0;
getline(cin, name); //Get the full name
temp = getnext(name, " ", index); //Get first name
if (index == string::npos) {
cout << error;
return -1;
}
cout << "First name: " << temp << endl;
temp = getnext(name, " ", ++index); //Get middle name
if (index == string::npos) {
cout << error;
return -1;
}
cout << "Middle Name: " << temp << endl;
temp = getnext(name, " ", ++index); //Get last name
cout << "Last name: " << temp << endl;
return 0;
}