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.
Related
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;
}
}
Giving 5 inputs, program will check which entered character is the greater (assume characters are alphabets here only).
This is the code I've written (All variables are of char data type).
Problem is, it's printing the last entered character every time which makes it obvious the logic is faulty..
Here's the code I've written:
cout << "Enter a character ";
cin >> chr;
for (int i = 0; i < 4; i++)
{
cout << "Enter a character ";
cin >> chr2;
if (chr > chr2)
{
store = chr;
}
else
{
store = chr2;
}
chr = chr2;
}
cout << "Greater character is "<< store << endl;
You are making your code far too complex! What you need to do is first set your 'rolling' maximum (the store variable) to a value lower than any possible input (let's say 0) then run a single loop to read in each of the test characters. On each input, compare the given character to your 'rolling' max and, if it's greater, set that rolling max to the given input.
Something like this:
char store = 0, chr;
for (int i = 0; i < 5; ++i) {
cout << "Enter a character ";
cin >> chr;
if (chr > store) store = chr;
}
cout << "Greatest character is "<< store << endl;
Feel free to ask for further clarification and/or explanation.
The problem here is that you are always comparing with the previous character, not the biggest-seen character.
In my opinion, the control flow can be simplified. Try something like this:
/* Rather than pull the first iteration out of the loop, begin with the minimum value */
char greatest = std::numeric_limits<char>::min();
for(int i = 0; i < 5; i++)
{
std::cout << "Enter a character: " << std::endl;
char input;
std::cin >> input;
/* We only need to replace `greatest` with `input` if `input` is greater */
if(input > greatest)
{
greatest = input;
}
}
std::cout << "Greatest character is: " << greatest << std::endl;
Your code chr = chr2; in the last before line tells the code to store the last entered value in the chr and this means you are comparing only the last and last before entered value in the program,
To change the program to suit your need , Change chr = store; which tells the program to store the greatest char entered to be stored inside char variable .
cin >> chr;
for (int i = 0; i < 4; i++)
{
cout << "Enter a character ";
cin >> chr2;
if (chr > chr2)
{
store = chr;
}
else
{
store = chr2;
}
chr = store;
}
cout << "Greater character is "<< store << endl; ````
Hope this helps!!
I want to create a program which is able to count the characters in a word.
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
do
{
string inputWord = "";
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
do
{
char searchCh = '0';
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
}while(searchCh.size()<1 && searchCH.size()>1);
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
char ch = word.at(i);
// if the character matches the character we're looking for
if(searcCh==ch)
// increment counter
{
counter++; // counter = counter + 1
}
}
// output the number of times character appears
cout << "the word " << word << " contain character " << searchCh << "is" << counter;
return 0;
}
and I always get the error: inputWord was not declared.
What is the cause this error?
You should read about scopes. Variables in c++ have visibility and lifetime in scope, in which the were declared. For instance, inputWord is visible and exists only in the first do-while loop. Move its declaration above loop. Your code has many such errors. Moreover, I do not see, where is counter declared and it should be properly initialized.
You have mixed up a lot of variable names and used variables outside their scope.
Here is a working version of your code with a few debugs:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
string inputWord = "";
char searchCh = '0';
char ch;
int counter=0;
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
ch = inputWord[i];
// if the character matches the character we're looking for
if(searchCh==ch)
// increment counter
counter++; // counter = counter + 1
}
// output the number of times character appears
cout << "the word " << inputWord << " contain character " << searchCh << " is " << counter;
return 0;
}
You declared the inputWord as string, please check your compiler works for that or not because some compilers do not take the specifier "string". Also searchCh, counter and word is also missing from your program. First of all declare these variables properly.
you should define the "inputWord" before start the while loop , like this :
string inputWord = "";
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
because "inputWord" is inside the loop ,
I'm required to find a character entered by the user in a for loop. I'd usually do
if (sentence[i] == 'e')
but since here, 'e' will be a one letter char variable, I don't know how to get that value to be compared. I can't just enter
if (sentence[i] == thechar)
but I also can't create a variable to contain the character in between quotation marks like
char2 = "\'" + thechar + "\'";
So how do I do it in this context? I'm not allowed to use other, more effective, more advanced methods. This is a basics course. Please help!
string word;
char letter;
cout << "Enter a word\n";
cin >> word;
cout << "What letter would you like to search for?\n";
cin >> letter;
for (int i = 0; i < word.length(); i++)
{
if (word[i] == letter)
{
cout << letter << " is the " << i + 1 << "character of " << word << endl;
}
}
You can create a variable where you ask for the letter the user wants, and use that variable to compare.
To find position of chosen letter you can use std::string.find(...)
std::string str = "My house is white.";
std::size_t pos = str.find('s');
std::cout << "Position: " << pos << std::endl;
Output:
Position: 6
For more informations go to http://www.cplusplus.com/reference/string/string/find/ page.
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.