Finding substring of string - c++

So, I'm just starting out this C++ course and we are doing strings now. For this assignment, what my professor wants me to do is to find a string within a string and to print it out and at a position. This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Please enter a phrase: " << endl;
string phrase;
getline(cin, phrase);
cout << "Please enter a possible substring of the phrase: " << endl;
string phrase_2;
getline(cin, phrase_2);
string pos = phrase.substr(phrase_2);
cout << phrase_2 << "was found at position " << pos << endl;
return 0;
}
I have tried multiple hours trying to get the code to print out the position. This might be totally wrong and I apologize for that, but if you could help me out, I would appreciate it.

You need to use std::string::find to get the position of a sub string within a string:
Using your code as an example:
int main ()
{
cout << "Please enter a phrase: \n";
string phrase;
getline(cin, phrase);
cout << "Please enter a possible substring of the phrase: \n";
string phrase_2;
getline(cin, phrase_2);
std::size_t position = phrase.find(phrase_2);
if (position != std::string::npos)
std::cout << phrase_2 << " was found at position " << position << "\n";
return 0;
}

Google is your friend...
Instead of
string pos = phrase.substr(phrase_2);
You should use
size_t pos = phrase.find(phrase_2);

Related

Converting an octal number to decimal number using char only

I am new here and new to c++ as well.
I just started my first year at school and I have been given an assignment in which one of the questions is to convert an octal number to a decimal number using Char only.
The task is to create a program that receives chars from the user and where the length of the number is not known in advance. The user should press '\t' in order to start calculating to a decimal number.
I don't really understand how it works.Because if I code a simple algorithm such as:
char ch;
cin<<ch;
cout>>ch>>endl;
and I give it 67, it will print 6 only. That means that it reads every char separately, doesn't it?
Could someone please help me understand it by showing me the algorithm for this problem or explaining to me how char works?
Thanks a lot
Coral
You will get enough info on how to read from stdin char by char.
please go through this link.
http://www.cplusplus.com/forum/articles/6046/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string input = "";
// How to get a string/sentence with spaces
cout << "Please enter a valid sentence (with spaces):\n>";
getline(cin, input);
cout << "You entered: " << input << endl << endl;
// How to get a number.
int myNumber = 0;
while (true) {
cout << "Please enter a valid number: ";
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber)
break;
cout << "Invalid number, please try again" << endl;
}
cout << "You entered: " << myNumber << endl << endl;
// How to get a single char.
char myChar = {0};
while (true) {
cout << "Please enter 1 char: ";
getline(cin, input);
if (input.length() == 1) {
myChar = input[0];
break;
}
cout << "Invalid character, please try again" << endl;
}
cout << "You entered: " << myChar << endl << endl;
cout << "All done. And without using the >> operator" << endl;
return 0;
}

String phrase ends at space?

I am wringing a simple code to learn more about string. When I ran my code it would not print my last name. Can someone explain why? I used string phrase to store it and it only appears to have stored my first name. Here is the code.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting;
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
cin >> phrase;
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
I used string phrase to store it and it only appears to have stored my first name.
That makes sense.
cin >> phrase;
will stop reading when it encounters a whitespace character in the input.
To read the full name you can use one of the following approaches.
Use two calls to cin >>.
std::string first_name;
std::string last_name;
cin >> first_name >> last_name;
Use getline to read the entire line. getline will read everything in a a line, including whitespace characters.
getline(cin, phrase);
When you call cin >> phrase;, it only reads the string up to the first non-space character. If you want to include spaces in your name, best goes with getline(cin,phrase);.
IMPORTANT: getline() will reads whatever it is in the stream buffer up to the first \n. It means that when you enter cin >> greeting;, if you hit ENTER, getline() will read everything before that \n that is not already read, which is NOTHING into your phrase variable, making it an empty string. An easy way out is to call getline() twice. E.g.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting; //IMPORTANT: THIS ASSUME THAT GREETING IS A SINGLE WORD (NO SPACES)
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
string rubbish_to_be_ignored;
getline(cin,rubbish_to_be_ignored); //this is going to read nothing
getline(cin, phrase); // read the actual name (first name and all)
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
Assuming you store that code in the file stackoverflow.cpp. Sample run:
Chip Chip#04:26:00:~ >>> g++ stackoverflow.cpp -o a.out
Chip Chip#04:26:33:~ >>> ./a.out
Exercise 3B
Kaitlin Stevers
String arrays
Please enter a greeting:
Hello
The greeting you entered was: Hello
Enter your full name
Kaitlin Stevers
Hello, how are you today Kaitlin Stevers?
Tested on ubuntu 14.04

C++, I want to search one character in string, and output all words which contain this character

I have one string for example, " Today is Monday " if the user types "o", the program must output "Today and Monday" because they contain "o".
My code is this but its not working its only search substring.
#include <iostream>
#include <string.h>
using namespace std;
#define size 100
int main()
{
char str[size];
char searching_string[size];
cout << " Enter String : ";
cin.getline(str,100);
cout << " String : " << str;
cout << " Enter Search String : ";
cin.getline(searching_string,size);
cout << endl << endl;
cout << strstr(str,searching_string);
cin.get();
cin.get();
return 0;
}
Besides of the Quality of this Question.
I think strchr() is what you are looking for.
Link
Hang on.

Checking a string to match a Char variable

I have written a short program that takes a user input and then checks a string for a match to the users input but I need to add another function that checks make sure that the user input is in the string and if its not to return an error.
Here is my code for reference:
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,’ ";
int main()
{
char letter; //Variable holding user entered letter
cout << "Please enter letter in the aplhabet:" << endl;
cin >> letter;
cout << "The Position of " << letter << " in the string is: " << ALPHABET.find(letter) << endl;
return 0;
}
I think I ought to add an if/else statement that first checks to see if the input is correct and if it is output the position in the string and if not return and error.
If you wanted to be fancy, you could write your own function. However, string::find() is ok. All you need to check is whether or not the returned index is valid or not.
// Example program
#include <iostream>
#include <string>
using namespace std;
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,’ ";
int main()
{
char letter; //Variable holding user entered letter
string::size_type index; //Index where char is found in string
cout << "Please enter letter in the aplhabet:" << endl;
cin >> letter;
index = ALPHABET.find(letter);
if (index == string::npos)
cout << "Error, letter not found" << endl;
else
cout << "The Position of " << letter << " in the string is: " << index << endl;
return 0;
}
An if/else statement sounds good. And if that doesn't work, there are other multiple ways that it could.

C++ Menu and String Searching within Array

When I enter this code and try to run it, it isn't working when the user selects option 1, to enter some text and a string to search for within their text. It outputs "enter text" and then "enter string to search" immediately after, without giving the user the chance to input some text. What is wrong?
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
char choice[1];
cout << endl;
cout << endl;
cout << "--MENU--" << endl;
cout << "1. Pattern Matching" << endl; // search for string within text
cout << "2. Sorting Techniques" << endl; // generate and then sort 10 random numbers
cout << "Enter your choice: " << endl;
cout << endl;
cin >> choice;
cout << endl;
if (choice[0] == '1') // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << "." << endl;
}
else
{
cout << "Did not find text." << endl;
}
}
This is because cin >> choice reads part of the current input line for the choice entered by the user. The first getline() call reads the remaining part of the input line immediately following the choice entered by the user. You need to ignore the rest of the input line after the choice.
cin >> choice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You will also need to add #include <limits> to the beginning of your code in order to pull in numerical_limits.
It looks as though you are defining some sort of char array for the user response. I would tend to make that a non-zero integer type with an exception if the choice is neither 1 nor 2. There are also some shortcuts for output formatting that reduces lines of code. Also, you would want to include the standard string class to accept the string. Maybe try something like the following:
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
int choice;
cout << "\n--MENU--\n"l;
cout << "1. Pattern Matching\n"; // search for string within text
cout << "2. Sorting Techniques\n"; // generate and then sort 10 random numbers
cout << "Enter your choice:\n";
cin >> choice+"\n";
if (choice == 1 && choice > 0 && choice != 0) // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << ".\n";
}
else
{
cout << "Did not find text.\n";
}
}}}