EZ

Eduzan

Learning Hub

Eduzan
Eduzan / C++

Strings

C++ offers two primary ways to handle strings: traditional C-style character arrays and the std::string class from the standard library, which provides a more flexible, dynamic approach.

1. C-Style Strings: C-style strings are simple character arrays ending with a null character ('\0'), inherited from the C language. They are efficient but lack the advanced features of the std::string class.

Example:

#include <iostream>
using namespace std;

int main() {
    char s[] = "Programming";
    cout << s << endl;
    return 0;
}

Output:

Programming

2. std::string Class : The std::string class, part of the <string> library, introduces numerous advantages over C-style strings, such as dynamic sizing and various member functions for easy manipulation.

#include <iostream>
using namespace std;

int main() {
    string str("Hello, C++");
    cout << str;
    return 0;
}

Output:

Hello, C++

Defining Strings with Repeating Characters

To define strings with repeated characters:

Example:

#include <iostream>
using namespace std;

int main() {
    string str(4, 'A');
    cout << str;
    return 0;
}

Output:

AAAA

Methods for Taking String Input

1. Using cin
2. Using getline
3. Using stringstream

1. Using cinThe simplest method is to use cin with the extraction operator (>>), which reads input until a space is encountered.

Example:

#include <iostream>
using namespace std;

int main() {
    string s;
    cout << "Enter a word: ";
    cin >> s;
    cout << "Entered word: " << s << endl;
    return 0;
}

Output:

Enter a word: Hello
Entered word: Hello

2. Using getlineThe getline() function reads an entire line of input, including spaces.

Example:

#include <iostream>
using namespace std;

int main() {
    string s;
    cout << "Enter a sentence: ";
    getline(cin, s);
    cout << "Entered sentence: " << s << endl;
    return 0;
}

Output:

Enter a sentence: C++ is powerful!
Entered sentence: C++ is powerful!
End of lesson.