C++ Tutorial: Strings and C-Strings

GFreak45

I didnt slap you, i high 5'd your face.
Reaction score
130
Uses: Getting Started and Functions and Variables

Strings:

Strings in C++ are an array of 1 byte numbers (characters). As C++ is an object oriented program there is a simple class that handles strings for you. You can access this class by including the string header. The string class manages sizes, re-sizing, appending, concating, and assigning string values.

The string class has a few constructors:
  • Default, initializes an empty string (no characters)
  • Overloaded, takes a c-string ("string inside quotes or array of characters")
  • Overloaded, takes a string (copies the string)
Useage examples:
Code:
string Name = "John"; // can also be written like so: string Name ("John")
 
string Nothing;
 
string NameCopy = Name;

The string class also comes with a few interesting operators:
  • operator = - assignment operator, changes one string's array of characters to equal another string's array, or a c-string
  • operator += - append operator, adds one string on to the end of the first
  • operator + - concatenate string operator, combines 2 strings and returns one
  • operator [] - allows you to attain the character in that position of the array
Useage Example:
Code:
string One = "a"; //One = "a"
 
One += "bcd"; //One = "abcd"
 
string Two = One;
One = (Two + "efg"); //One = "abcdefg"
 
One[0] = "1"; // One = "1bcdefg"

There are also a few great utility functions that come with the string class:
  • size - the ammount of characters in the string
  • substr - substring, a piece of the original string between 2 indeces
  • replace - replaces part of a string
  • getline - static, gets an entire line of an iostream (cin, fstreams, etc)
Useage examples:
Code:
string Sentence = "This is a sentence.";
 
string Word = Sentence.substr(0, 4); //start position, length - "This"
 
Sentence.replace(0, 0, Word);
/* replaces the substring with the given string, since this is a substring of 0 size
at place 0, it just inserts Word into the beginning of Sentence,
now Setence = "ThisThis is a sentence." */

Getline is a little more complex:
Code:
string line;
while (cin.peek() == '\n') cin.ignore();
getline(cin, line);

getline takes an iostream (cin or a file stream) and reads from the current position in the stream until it runs into a '\n' (new line). What it does not take into account, is that when you use the >> (get formated data) operator, a delimiter is left on the end, be it a space, a newline or a tab, therefore we need to make sure tha there are no hanging newlines before we get each line, that is the: while (cin.peek() == '\n') cin.ignore(), which checks if the next character to get is a newline without removing it, then if it is, it removes it via cin.ignore()

Full useage example:
Code:
#include <iostream>
#include <string>
 
using namespace std;
 
int main ()
{
    string name;
    char again = 'y';
    while (again != 'n')
    {
        cout << "What is your name? ";
        while (cin.peek() == '\n') cin.ignore();
        getline(cin, name);
        cout << "So your name is " << name << "\n"
            << "How old are you? ";
        int age = 0;
        cin >> age;
        cout << "So your name is " << name << " and you are " << age << " years old.\n"
            << "Would you like to input someone elses information? (y/n): ";
        cin >> again;
        cout << "\n";
    }
    cout << "\n";
    system("Pause");
    return 0;
}

C-Strings:

C-Strings are used in C and a little in C++, they were used in C because Object Oriented Programming had not taken a foothold yet. A C-String is an array of characters, as simple as that. A string can be initialized via: string s = "some sentence"; However, a C-String is initialized like so:
Code:
char s[] = { 's', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e', '\n' };
The same way an array is initialized, but with characters rather than quotes, a character has the ' character around it to reference a number (UTF8 code) that represents that character, for instance '0' is the same as 31, so this is really just an array of numbers. There are a few interesting ways to interact with c-strings:
  • printf - prints the c-string (like cout) "print formated data"
  • scanf - gets information from the iostream
  • fprintf - prints information to a file (used the same as printf)
  • fscanf - file scan
  • We also gain use of the iostream::getline function (cin.getline)
  • The std::string::c_str function can get a constant C-String from any string (string.c_str)
In order to use these functions you must include the cstdio.h library
Useage Examples:
Code:
char s[] = { 's', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e', '\n' };
 
printf("%s \n", s); //%s is the formatted data type
 
int input;
scanf("%d", &input);
/* %d is the signed int type, the & operator means address of
(so the scanf can edit the value of input, not needed with arrays) */

fscanf and fprintf are the same but interacting with files, for more information on printf and scanf click those links.

The getline function is somewhat like the static getline, but it is meant for a C-String.
Code:
#include <cstdio.h>
#include <iostream>
 
using namespace std;
 
int main ()
{
    char name[30];
    char again = 'y';
    while (again != 'n')
    {
        printf("%s", "What is your name? ");
        scanf("%s", name);
        printf("%s", "So your name is ");
        printf("%s \n", name);
        printf("%s", "How old are you? ";
        int age = 0;
        scanf("%d", &age);
        printf("%s", "So your name is ");
        printf("%s", name);
        printf("%s", " and you are ");
        printf("%d", &age);
        printf("%s \n", " years old.");
        printf("%s", "Would you like to input someone elses information? (y/n): ");
        scanf("%c", &again);
        printf("%s \n", "");
    }
    printf("%s \n", "");
    system("Pause");
    return 0;
}

The output of both full useage examples should be the same.
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
I'm a bit lost with C-String. You say they must be initialized like an array, isn't there a way to initialize with quotes like
Code:
char* a = "I like trains.";
 

GFreak45

I didnt slap you, i high 5'd your face.
Reaction score
130
yes, but that is not its own instance. Basically, if you use that sentence again exactly as put there then it will use the same reference in memory. So if you do something like this:
Code:
char* a = "I like trains.";
a[3] = s; //or scanf("%s", a);
it will modify that array in memory for any other values of the same string, ie:
Code:
char* otherString = "I like trains."; //after the first code
//otherString actually equals "I lske trains."
so, yes that will work, but it should not be modified unless you create an entirely new array to hold the values in.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?
  • The Helper The Helper:
    Happy Thursday!
    +1
  • Varine Varine:
    Crazy how much 3d printing has come in the last few years. Sad that it's not as easily modifiable though
  • Varine Varine:
    I bought an Ender 3 during the pandemic and tinkered with it all the time. Just bought a Sovol, not as easy. I'm trying to make it use a different nozzle because I have a fuck ton of Volcanos, and they use what is basically a modified volcano that is just a smidge longer, and almost every part on this thing needs to be redone to make it work
  • Varine Varine:
    Luckily I have a 3d printer for that, I guess. But it's ridiculous. The regular volcanos are 21mm, these Sovol versions are about 23.5mm
  • Varine Varine:
    So, 2.5mm longer. But the thing that measures the bed is about 1.5mm above the nozzle, so if I swap it with a volcano then I'm 1mm behind it. So cool, new bracket to swap that, but THEN the fan shroud to direct air at the part is ALSO going to be .5mm to low, and so I need to redo that, but by doing that it is a little bit off where it should be blowing and it's throwing it at the heating block instead of the part, and fuck man
  • Varine Varine:
    I didn't realize they designed this entire thing to NOT be modded. I would have just got a fucking Bambu if I knew that, the whole point was I could fuck with this. And no one else makes shit for Sovol so I have to go through them, and they have... interesting pricing models. So I have a new extruder altogether that I'm taking apart and going to just design a whole new one to use my nozzles. Dumb design.
  • Varine Varine:
    Can't just buy a new heatblock, you need to get a whole hotend - so block, heater cartridge, thermistor, heatbreak, and nozzle. And they put this fucking paste in there so I can't take the thermistor or cartridge out with any ease, that's 30 dollars. Or you can get the whole extrudor with the direct driver AND that heatblock for like 50, but you still can't get any of it to come apart
  • Varine Varine:
    Partsbuilt has individual parts I found but they're expensive. I think I can get bits swapped around and make this work with generic shit though
  • Ghan Ghan:
    Heard Houston got hit pretty bad by storms last night. Hope all is well with TH.
  • The Helper The Helper:
    Power back on finally - all is good here no damage
    +2
  • V-SNES V-SNES:
    Happy Friday!
    +1
  • The Helper The Helper:
    New recipe is another summer dessert Berry and Peach Cheesecake - https://www.thehelper.net/threads/recipe-berry-and-peach-cheesecake.194169/

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top