Tutorial 5: Streams & String Manipulation//Bonus: Search & Replace program Example!//Learn by doing

in #programming8 years ago

header

2-3 more posts and this the beginners tutorial will almost be finished, and you will be able to make some nice basic programs!

Don't fret! I'll continue by giving some example programs for you to follow and play with ^_^

This lesson will cover:

Tutorial contents:

  1. Streams
  2. String Manipulation

Now we are already slowly learning how to make a user database.

And in the next tutorial we will also learn how to work with files!

First off let's talk about streams:
streams
Not that kind of stream, we're reffering to the...

StringStream!


It's very easy to understand streams, which is probably why I won't talk too much about it.

After all, nowadays you see so many "streaming" websites you should be able to guess what this is.
Like a twitch.tv streamers basically are individuals who stream to an audience, this does pretty much the same.
Except of course, our audience isn't so judgy!

Basic example of a stringstream:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    stringstream ss;
    string a = "myfirststring";
    int ivar = 1;
    float fvar = 1.1;
    double dvar = 2.2;
    ss << a << ivar << fvar << dvar;
    cout << ss.str(); //This prints the entire input of the buffer as a string
}

So it can store pretty much all you need...

Now let's see what else we can do with it by examples:

#include <iostream>     
#include <string>
#include <sstream>      
using namespace std;

int main () 
{

  stringstream ss;
  ss << "Hello" << ' ' << "world" << ' ' << "!"; //Notice the ' ' space delimiter to separate them!
  string a,b,c;                                  //Without "' '" all of the strings would be treated as one!
  ss >> a >> b >> c; //Notice how they are treated as different objects because we used ' '
  cout << "A: " << a << '\n';
  cout << "B: " << b << '\n';
  cout << "C: " << c << '\n';
  string result = ss.str();// to get the entire string
  cout << "Result Method 1 = " << result << endl;
  ss >> result; //Or you might aswell do it this way!
  cout << "Result Method 2 = " << result << endl;
  cout << "Direct ss Output = " << ss.str();
  return 0;
}

You of course can set the buffer of the stream directly.

#include <iostream>     
#include <string>
#include <sstream>      
using namespace std;
int main () 
{
stringstream ss;
ss.str("Hello world!");
cout << ss.str();
}

Remember how I called it a buffer?

Hehe, now I'm going to show you something I think you will like, at least I sure did!

#include <iostream>     
#include <string>
#include <sstream>      
using namespace std;
int main () 
{
stringstream ss;
ss.str("Elem1 Elem2 Elem3"); //Storing these 3 elements in buffer
string mystr;
int numelements = 0;
while(ss >> mystr) //Remember how I said earlier they are treated as different objects and not a single string?
{                  //This is why.
    numelements++; //Let's count them, why not?
    cout << "Element: "<< mystr << endl;
}
cout << "Number Of Elements:" << numelements << endl;
system("pause");
//As a secondary side, you can also clear the buffer!
cout << "Before being cleared:" << ss.str() << endl;
ss.str("");
numelements = 0;
cout << "After  being cleared:" << ss.str() << endl;
cout << "Elements: " << numelements << endl;
}

You know what that means right?

img
Next step towards multiple user authentication program ^_^

#include <iostream>     
#include <string>
#include <sstream>      
using namespace std;
/*
Note:
Not quite a good idea if you're already thinking of making a huge database and adding another check!
If this interests you wait for my next tutorials.
*/
int main () 
{
    stringstream ss;
    ss.str("Alex Amy John Ellie Dan Ned Doe"); //Users
    string input, usr;
    cout << "Only certain people can see this, who would you be?\n";
    cin >> input;
    bool auth = false;
    while(ss>>usr)
    {
        if(input == usr)
        {
            auth = true;
            break; // This breaks out of the while loop(remember the switch?) //
        }          // If you used continue, it would simply skip over this step and go untill the end.
    }
    if(auth == true)
    {
        cout << "Welcome, "<< usr <<"!\nSuper Secret Stuff\n";
    }
    else
    {
        cout << "You are not allowed to see this!\nShoo!\n";
    }
    
}

Now that I've shown you what stringstream is and why it's very useful, it's time to move on to one of your worst nightmares.

String Manipulation


Okay, So we do have strings, they're nice right?
Pretty useful eh?
Not quite, how would you even begin to search for any part of a string for example?
Or say that with the above user input we want the account not to be case sensitive what do we do?
Ideas?
No? I thought so.
This is why I'm going to give you a few ideas as to how you can interact with strings.

#include <iostream>     
#include <string>
#include <locale> //To lowercase
using namespace std;
string lcase(string fstr)
{
    string rstr; //resulting string
    locale loc;
    for (string::size_type i=0; i<fstr.length(); ++i) //String::size_type is required by the tolower function
    {                               
    rstr = rstr + tolower(fstr[i],loc);
    }
    return rstr;
}
string ucase(string fstr)
{
    string rstr; //resulting string
    locale loc;  //Used to find upper or lower case equivalent of every letter.
    for (string::size_type i=0; i<fstr.length(); ++i) //String::size_type is required by the tolower function
    {                               
    rstr = rstr + toupper(fstr[i],loc);
    }
    return rstr;
}
int main () 
{
    string str("Hello there!");
    string strlow = lcase(str);//Of course if you've learned functions you can save that and use it.
    string strupp = ucase(str);//Or you could use it without a function and do it manually each time
                               //Do try to play with functions they simplify your life.
    //Let's say we want to convert a string from uppercase to lower case
    cout << "Str Contains: "   << str << endl
         << "It's length is: " << str.length()<< endl
         << "\n";
    cout << "Lowercase: " << strlow << endl;
    cout << "Uppercase: " << strupp << endl;
    
}

That's all very useful, now let's talk about how to search for something within a string.

img

#include <iostream>     
#include <string>
#include <locale> //To lowercase
using namespace std;
int main()
{
    string db("string function int float double string char long bool");
    cout << "What word do you want to search for in our database?\n";
    string input;
    size_t found;
    cin >> input;
    found = db.find(input);
    if(found != string::npos) //Check to see if we found anything before the end of the db string.
    {
    cout << "Found word at:" << found; 
    }
    else
    {
        cout << input << " is not in the database!";
    }
    return 0;
}

Fairly nice, let's also show you how you can replace something inside the string.

#include <iostream>     
#include <string>
#include <locale> //To lowercase
using namespace std;
int main()
{
    string db("string function int float double string char long bool");
    cout << "What word do you want to search for in our database?\n";
    string input;
    size_t found;
    cin >> input;
    found = db.find(input);
    if(found != string::npos)
    {
    cout << "Found word at:" << found << endl; //found the word at x position of the string (string[x])
    cout << "Would you like to replace it with some other word?\nEnter 1 for yes or 0 for no.\n";
    int swc;
    cin >> swc;
    switch(swc)
    {
        case 0:
        {
            cout << "Bye !\n";
            break;
        }
        case 1:
        {
            system("cls");
            cout << "Enter the new word to replace \"" << input << "\" With!\n";
            string input2;
            cin >> input2;
            db.replace(db.find(input),input.length(),input2);
            cout << db;
            break;
        }
        default:
        {
            cout << " no such option, aborting!";
            break;
        }
    }
    }
    else
    {
        cout << input << " is not in the database!";
    }
    return 0;
}

And so on and so forth now you have a little more understanding of how you could use strings.
Obviously I must reffer you to look over the string in itself
You should be able to figure the rest of it on your own over there.

Custom Headers


get used to headers we are going to use them in the next tutorials so you should have an idea about them
How to make a header file:

  1. create a text file called myheader.txt
  2. rename it to myheader.h
  3. in devc++ right click on your project->add to project->myheader.h(browse to your newly created header)
  4. make it contain a function such as:
    myheader.h
#include <iostream>
using namespace std;
int hellomsg()
{
    cout << "Hello my beautiful human friend!\n";
}

main.cpp //Notice you don't need to include iostream & using namespace std again. because it takes them from the header you've made.

#include "myheader.h"
int main()
{
    hellomsg();
    cout << "hi\n";
}

Great, now for the next tutorials I'm going to make, we can almost get to creating an actual application, which is probably how I'm going to continue the tutorials after giving you the basics.

Please don't forget to like & follow this tutorial if you liked it.

Feel free to ask me anything in the comments
The header is of my own design
All written content is my own work.
All memes were generated using imgflip.com
Link to streams wallpaper

Coin Marketplace

STEEM 0.22
TRX 0.26
JST 0.040
BTC 99032.11
ETH 3469.45
USDT 1.00
SBD 3.22