1

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!

3
  • I'm required to find a character - Something in quotation marks is not a character. Commented Jul 25, 2014 at 2:56
  • It might not be 'e'. I have to cin >> thechar. So if user enters u, my condition will have to check for 'u' but I don't know how to create a variable that converts string u to string 'u'. I do not get the { /*...*/} part. Commented Jul 25, 2014 at 3:03
  • @blue0, '' is for character literals. Once you have a char, you don't need to add the single quotation marks or anything special. Commented Jul 25, 2014 at 3:14

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. All I was taught is to declare strings as char word[maxwordlength]; so I tried to work that way. In the end this is better done the same way as pretty much all other languages.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.