dimanche 2 février 2020

C++ Strings: size_t and string::npos

I'm a beginner programmer and I'm trying to understand this piece if code and how it works...

So here is the code:

#include <iostream>
#include <string>  //C++ Strings Library
using namespace std;

int main() {
  string s1 {};
  string wordFind {};
  s1 = "The secret word is Boo";
    cout << "Enter the word to find: ";
    cin >> wordFind;
    size_t position = s1.find(wordFind);
     if (position != string::npos)
        cout << "Found " << wordFind << " at position: " << position << endl;
     else
        cout << "Sorry! " << wordFind << " not found" << endl;
    return 0;
}

These are the questions that I actually have:

  1. What is size_t and when should we use them exactly?(All I know is that we should use them for array indexing and loop counting)
  2. Why did we use size_t here? couldn't it be like this?:

position = s1.find(wordFind);

  1. What is position exactly?(I mean is it made up or is it a part of C++?)
  2. Does the if condition mean to search the word untill the end of the string?

Edit:Thank you everyone for helping me...I appreciate it:)

Aucun commentaire:

Enregistrer un commentaire