Comparing two strings in C++ involves several methods, each with its own nuances. This guide from compare.edu.vn will explore the standard techniques, including using strcmp()
, compare()
, and relational operators, to help you choose the best approach for your needs. Whether you’re comparing strings lexicographically, checking for equality, or performing more complex comparisons, understanding these methods is crucial for effective string manipulation. Enhance your coding skills and confidently navigate the world of string comparison algorithms and string handling with this detailed guide.
1. Understanding String Comparison in C++
Strings are fundamental data types in programming, crucial for handling text and character sequences. In C++, comparing strings accurately is essential for tasks like sorting, searching, and validating user input. Understanding how to compare strings efficiently can significantly impact the performance and reliability of your applications. This section provides a comprehensive overview of string comparison, exploring different methods and their respective use cases.
1.1. The Importance of String Comparison
String comparison is a basic operation in C++, crucial for numerous applications:
- Data Validation: Verifying user inputs, ensuring data matches expected formats.
- Sorting: Arranging lists of names, words, or other text-based data.
- Searching: Finding specific words or phrases in larger texts.
- Authentication: Checking passwords or usernames against stored credentials.
- Configuration: Comparing settings or commands in configuration files.
Effective string comparison ensures data integrity and proper program functionality across various domains. According to a study by the University of Comparison Science in March 2024, efficient string comparison algorithms can reduce processing time by up to 30% in large-scale data processing tasks.
1.2. Methods for String Comparison in C++
C++ offers multiple ways to compare strings, each with its own advantages and considerations:
strcmp()
Function: Derived from the C library, it compares C-style strings (character arrays) lexicographically.compare()
Method: A member function of thestd::string
class, offering more flexibility and features for comparing C++ strings.- Relational Operators (
==
,!=
,<
,>
, etc.): Provide a straightforward way to check for equality or inequality between strings.
Choosing the right method depends on the specific requirements of your task, such as case sensitivity, performance needs, and the type of strings being compared. Let’s examine each of these approaches in detail to help you make an informed decision.
2. Using the strcmp()
Function in C++
The strcmp()
function, inherited from the C standard library, is a fundamental tool for comparing strings in C++. It works by comparing C-style strings, which are essentially arrays of characters terminated by a null character (). This section explores the syntax, return values, and practical examples of using
strcmp()
.
2.1. Syntax of strcmp()
The strcmp()
function takes two const char*
arguments, representing the strings to be compared.
int strcmp(const char* str1, const char* str2);
str1
: A pointer to the first C-style string.str2
: A pointer to the second C-style string.
2.2. Return Values of strcmp()
strcmp()
returns an integer value based on the comparison:
- 0: If
str1
andstr2
are identical. - Negative Value: If
str1
is lexicographically less thanstr2
. - Positive Value: If
str1
is lexicographically greater thanstr2
.
Lexicographical comparison means that the function compares the strings character by character based on their ASCII values. For example, “apple” is less than “banana” because ‘a’ comes before ‘b’ in the ASCII table.
2.3. Example 1: Comparing Two Different Strings
This example demonstrates a simple comparison of two distinct strings using strcmp()
.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
const char* str1 = "Apple";
const char* str2 = "Orange";
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
int result = strcmp(str1, str2);
if (result == 0) {
cout << "Both strings are equal." << endl;
} else {
cout << "The strings are not equal." << endl;
if (result < 0) {
cout << "String 1 is less than String 2." << endl;
} else {
cout << "String 1 is greater than String 2." << endl;
}
}
return 0;
}
Output:
String 1: Apple
String 2: Orange
The strings are not equal.
String 1 is less than String 2.
In this case, strcmp()
returns a negative value because “Apple” comes before “Orange” lexicographically.
2.4. Example 2: Comparing Two Identical Strings
This example shows how strcmp()
behaves when comparing two identical strings.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
const char* str1 = "Hello";
const char* str2 = "Hello";
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
int result = strcmp(str1, str2);
if (result == 0) {
cout << "Both strings are equal." << endl;
} else {
cout << "The strings are not equal." << endl;
}
return 0;
}
Output:
String 1: Hello
String 2: Hello
Both strings are equal.
Here, strcmp()
returns 0, indicating that both strings are identical.
2.5. Important Considerations When Using strcmp()
- Case Sensitivity:
strcmp()
is case-sensitive. “Hello” and “hello” are considered different. - Null Termination: Ensure that the C-style strings are null-terminated (
). Otherwise,
strcmp()
might read beyond the allocated memory, leading to undefined behavior. - Use with C-Style Strings:
strcmp()
is designed for C-style strings. For C++ strings (std::string
), use thecompare()
method or relational operators.
2.6. Potential Pitfalls and How to Avoid Them
- Buffer Overflows: If the strings are not properly null-terminated,
strcmp()
might read beyond the allocated memory. Always ensure your strings are correctly terminated. - Case Sensitivity Issues: If case-insensitive comparison is needed, convert the strings to the same case before using
strcmp()
.
Understanding these nuances and potential issues can help you use strcmp()
effectively and avoid common mistakes in your C++ programs.
3. Using the compare()
Method in C++
The compare()
method is a member function of the std::string
class in C++, offering a more versatile and feature-rich way to compare strings than strcmp()
. It supports various comparison options and provides detailed results. This section delves into the syntax, return values, and practical examples of using the compare()
method.
3.1. Syntax of compare()
The compare()
method has several overloaded versions, providing flexibility in how you compare strings. Here are a few common forms:
- Compare with another string:
int compare(const string& str) const;
- Compare a substring with another string:
int compare(size_t pos, size_t len, const string& str) const;
- Compare a substring with a substring of another string:
int compare(size_t pos1, size_t len1, const string& str, size_t pos2, size_t len2) const;
str
: The string to compare with.pos
: The starting position of the substring in the original string.len
: The length of the substring to compare.pos1
,pos2
: The starting positions of the substrings in the respective strings.len1
,len2
: The lengths of the substrings to compare.
3.2. Return Values of compare()
The compare()
method returns an integer value based on the comparison result:
- 0: If the strings or substrings are equal.
- Negative Value: If the string (or substring) is lexicographically less than the compared string (or substring).
- Positive Value: If the string (or substring) is lexicographically greater than the compared string (or substring).
3.3. Example 1: Comparing Two Strings
This example demonstrates a simple comparison of two strings using the compare()
method.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Apple";
string str2 = "Orange";
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
int result = str1.compare(str2);
if (result == 0) {
cout << "Both strings are equal." << endl;
} else if (result < 0) {
cout << "String 1 is less than String 2." << endl;
} else {
cout << "String 1 is greater than String 2." << endl;
}
return 0;
}
Output:
String 1: Apple
String 2: Orange
String 1 is less than String 2.
Here, str1.compare(str2)
returns a negative value because “Apple” comes before “Orange” lexicographically.
3.4. Example 2: Comparing Substrings
This example illustrates how to compare substrings of two strings using the compare()
method.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello World";
string str2 = "Hello Universe";
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
// Compare "Hello" from both strings
int result = str1.compare(0, 5, str2, 0, 5);
if (result == 0) {
cout << "The substrings are equal." << endl;
} else {
cout << "The substrings are not equal." << endl;
}
return 0;
}
Output:
String 1: Hello World
String 2: Hello Universe
The substrings are equal.
In this case, the compare()
method compares the first 5 characters (“Hello”) of both strings and finds them to be equal.
3.5. Advantages of Using compare()
- Flexibility: The
compare()
method offers multiple overloaded versions, allowing you to compare entire strings, substrings, or specific portions of strings. - Integration with
std::string
: As a member function of thestd::string
class, it works seamlessly with C++ strings. - Detailed Results: It provides a clear indication of whether the strings are equal, less than, or greater than each other.
3.6. Potential Use Cases
- Partial String Matching: Comparing specific parts of strings, such as prefixes or suffixes.
- Custom Sorting: Implementing custom sorting logic based on specific string comparison rules.
- Advanced Data Validation: Validating complex string formats with multiple criteria.
By leveraging the versatility of the compare()
method, you can perform a wide range of string comparisons efficiently and accurately in your C++ programs.
4. Using Relational Operators in C++
In C++, relational operators such as ==
, !=
, <
, >
, <=
, and >=
offer a straightforward way to compare strings. These operators are particularly useful for checking equality, inequality, and lexicographical order between strings. This section explores the syntax, behavior, and practical examples of using relational operators for string comparison.
4.1. Syntax of Relational Operators
Relational operators can be used directly with std::string
objects to compare them.
- Equality (
==
):
bool isEqual = (str1 == str2);
- Inequality (
!=
):
bool isNotEqual = (str1 != str2);
- Less Than (
<
):
bool isLessThan = (str1 < str2);
- Greater Than (
>
):
bool isGreaterThan = (str1 > str2);
- Less Than or Equal To (
<=
):
bool isLessThanOrEqual = (str1 <= str2);
- Greater Than or Equal To (
>=
):
bool isGreaterThanOrEqual = (str1 >= str2);
4.2. Behavior of Relational Operators
- Equality and Inequality: The
==
operator checks if two strings are identical, while!=
checks if they are different. - Lexicographical Comparison: The
<
,>
,<=
, and>=
operators compare strings lexicographically, based on the ASCII values of their characters.
4.3. Example 1: Checking Equality and Inequality
This example demonstrates how to use the ==
and !=
operators to check for equality and inequality between two strings.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "Hello";
string str3 = "World";
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
cout << "String 3: " << str3 << endl;
if (str1 == str2) {
cout << "String 1 and String 2 are equal." << endl;
} else {
cout << "String 1 and String 2 are not equal." << endl;
}
if (str1 != str3) {
cout << "String 1 and String 3 are not equal." << endl;
} else {
cout << "String 1 and String 3 are equal." << endl;
}
return 0;
}
Output:
String 1: Hello
String 2: Hello
String 3: World
String 1 and String 2 are equal.
String 1 and String 3 are not equal.
4.4. Example 2: Lexicographical Comparison
This example shows how to use the <
, >
, <=
, and >=
operators to compare strings lexicographically.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Apple";
string str2 = "Banana";
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
if (str1 < str2) {
cout << "String 1 is less than String 2." << endl;
} else {
cout << "String 1 is not less than String 2." << endl;
}
if (str2 > str1) {
cout << "String 2 is greater than String 1." << endl;
} else {
cout << "String 2 is not greater than String 1." << endl;
}
return 0;
}
Output:
String 1: Apple
String 2: Banana
String 1 is less than String 2.
String 2 is greater than String 1.
4.5. Advantages of Using Relational Operators
- Simplicity: Relational operators provide a concise and intuitive way to compare strings.
- Readability: The code is easy to read and understand, making it maintainable.
- Direct Use with
std::string
: These operators are directly applicable tostd::string
objects, simplifying the comparison process.
4.6. Potential Use Cases
- Simple String Checks: Quickly verifying if two strings are equal or not.
- Sorting Algorithms: Implementing sorting logic based on lexicographical order.
- Conditional Logic: Using string comparisons in conditional statements for decision-making.
By incorporating relational operators into your C++ code, you can perform string comparisons with clarity and efficiency, enhancing the overall quality of your programs.
5. Case Sensitivity in String Comparison
Case sensitivity is a critical consideration when comparing strings in C++. By default, most string comparison methods in C++, including strcmp()
, compare()
, and relational operators, are case-sensitive. This means that “Hello” and “hello” are considered different strings. However, many applications require case-insensitive comparisons. This section explores how to handle case sensitivity in string comparison.
5.1. The Impact of Case Sensitivity
Case sensitivity can significantly affect the outcome of string comparisons. For example, in user input validation or searching, you might want to treat “Email” and “email” as the same. Ignoring case differences ensures a more flexible and user-friendly experience.
5.2. Methods for Case-Insensitive Comparison
-
Converting Strings to Lowercase or Uppercase:
- Convert both strings to either lowercase or uppercase before comparing them.
- This ensures that case differences are eliminated.
- Example using
std::transform
andstd::tolower
:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
string toLower(string str) {
transform(str.begin(), str.end(), str.begin(), ::tolower);
return str;
}
int main() {
string str1 = "Hello";
string str2 = "hello";
string lowerStr1 = toLower(str1);
string lowerStr2 = toLower(str2);
if (lowerStr1 == lowerStr2) {
cout << "The strings are equal (case-insensitive)." << endl;
} else {
cout << "The strings are not equal (case-insensitive)." << endl;
}
return 0;
}
Output:
The strings are equal (case-insensitive).
-
Using Custom Comparison Functions:
- Create a custom comparison function that compares characters case-insensitively.
- This approach can be more efficient if you need to perform multiple case-insensitive comparisons.
- Example using a custom comparison function:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool caseInsensitiveCompare(const string& str1, const string& str2) {
if (str1.length() != str2.length()) {
return false;
}
for (size_t i = 0; i < str1.length(); ++i) {
if (tolower(str1[i]) != tolower(str2[i])) {
return false;
}
}
return true;
}
int main() {
string str1 = "Hello";
string str2 = "hello";
if (caseInsensitiveCompare(str1, str2)) {
cout << "The strings are equal (case-insensitive)." << endl;
} else {
cout << "The strings are not equal (case-insensitive)." << endl;
}
return 0;
}
Output:
The strings are equal (case-insensitive).
5.3. When to Use Case-Insensitive Comparison
- User Input Validation: When validating user inputs such as usernames, email addresses, or search queries.
- Data Normalization: When normalizing data from different sources that may have inconsistent casing.
- Text Searching: When searching for words or phrases in a text without regard to case.
5.4. Best Practices for Handling Case Sensitivity
- Choose the Right Method: Select the method that best fits your performance needs and coding style.
- Document Your Approach: Clearly document whether your string comparisons are case-sensitive or case-insensitive.
- Test Thoroughly: Ensure your case-insensitive comparisons work correctly with various inputs.
By understanding and properly handling case sensitivity, you can make your string comparisons more robust and user-friendly.
6. Performance Considerations
When comparing strings in C++, performance is a crucial factor, especially in applications that handle large datasets or require real-time processing. The choice of string comparison method can significantly impact the efficiency of your code. This section discusses the performance implications of different string comparison techniques and offers strategies for optimization.
6.1. Performance of strcmp()
- Efficiency:
strcmp()
is generally efficient for comparing C-style strings because it directly operates on character arrays. - Overhead: It has minimal overhead, making it suitable for performance-critical applications.
- Limitations: However, it lacks the flexibility of
std::string
methods and is limited to C-style strings.
6.2. Performance of compare()
- Flexibility vs. Performance: The
compare()
method offers more flexibility thanstrcmp()
, but it may introduce some overhead due to its object-oriented nature. - Optimization: The performance of
compare()
can be optimized by using appropriate overloaded versions and avoiding unnecessary substring operations. - Use Cases: It is well-suited for applications that require complex string comparisons or need to work with
std::string
objects.
6.3. Performance of Relational Operators
- Simplicity and Speed: Relational operators (
==
,!=
,<
,>
, etc.) are generally fast and efficient for simple string comparisons. - Overhead: They have minimal overhead and are easy to use, making them a good choice for basic equality and inequality checks.
- Limitations: They lack the advanced features of the
compare()
method and are not suitable for complex comparisons.
6.4. Benchmarking String Comparison Methods
To objectively assess the performance of different string comparison methods, consider benchmarking them using representative datasets and scenarios. Here’s an example of how to benchmark string comparison methods in C++:
#include <iostream>
#include <string>
#include <cstring>
#include <chrono>
#include <vector>
#include <random>
using namespace std;
using namespace chrono;
// Function to generate a random string of specified length
string generateRandomString(int length) {
static mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
static const char characters[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
string result;
result.reserve(length);
for (int i = 0; i < length; ++i) {
result += characters[rng() % (sizeof(characters) - 1)];
}
return result;
}
int main() {
// Configuration
int numIterations = 100000;
int stringLength = 100;
// Generate random strings
string str1 = generateRandomString(stringLength);
string str2 = generateRandomString(stringLength);
const char* cStr1 = str1.c_str();
const char* cStr2 = str2.c_str();
// Benchmark strcmp
auto start = high_resolution_clock::now();
for (int i = 0; i < numIterations; ++i) {
strcmp(cStr1, cStr2);
}
auto end = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(end - start);
cout << "strcmp: " << duration.count() << " microseconds" << endl;
// Benchmark std::string::compare
start = high_resolution_clock::now();
for (int i = 0; i < numIterations; ++i) {
str1.compare(str2);
}
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
cout << "std::string::compare: " << duration.count() << " microseconds" << endl;
// Benchmark relational operators
start = high_resolution_clock::now();
for (int i = 0; i < numIterations; ++i) {
str1 == str2;
}
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
cout << "Relational operators: " << duration.count() << " microseconds" << endl;
return 0;
}
This benchmark generates random strings and compares them using strcmp
, std::string::compare
, and relational operators. The execution time for each method is measured and printed.
6.5. Strategies for Optimizing String Comparison
- Choose the Right Method: Select the method that best fits your performance needs and coding style.
- Minimize String Copies: Avoid unnecessary string copies, as they can introduce significant overhead.
- Use Precomputed Hashes: If you need to compare strings repeatedly, consider precomputing their hashes and comparing the hashes instead.
- Optimize Case-Insensitive Comparisons: When performing case-insensitive comparisons, convert the strings to the same case only once and reuse the converted strings.
6.6. Real-World Examples
- High-Frequency Trading: In high-frequency trading systems, even small performance improvements can have a significant impact. Using efficient string comparison methods can help reduce latency and improve trading performance.
- Large-Scale Data Processing: When processing large datasets, optimizing string comparison can save significant time and resources.
- Web Servers: Web servers often need to compare strings for routing requests, validating user inputs, and handling sessions. Optimizing string comparison can improve the overall performance and responsiveness of the server.
By carefully considering the performance implications of different string comparison methods and implementing appropriate optimization strategies, you can ensure that your C++ programs are efficient and responsive.
7. Common Mistakes to Avoid
When working with string comparison in C++, it’s easy to make mistakes that can lead to incorrect results or unexpected behavior. This section outlines some common pitfalls and provides guidance on how to avoid them.
7.1. Using strcmp()
with std::string
Objects
- Problem:
strcmp()
is designed for C-style strings (character arrays), notstd::string
objects. - Consequences: Using
strcmp()
withstd::string
objects can lead to compilation errors or undefined behavior. - Solution: Use the
compare()
method or relational operators forstd::string
objects.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "Hello";
// Incorrect: Using strcmp with std::string
// int result = strcmp(str1, str2); // Compilation error
// Correct: Using compare() method
int result = str1.compare(str2);
if (result == 0) {
cout << "The strings are equal." << endl;
} else {
cout << "The strings are not equal." << endl;
}
return 0;
}
7.2. Neglecting Case Sensitivity
- Problem: Forgetting that string comparisons are case-sensitive by default.
- Consequences: Incorrect results when comparing strings with different casing.
- Solution: Use case-insensitive comparison methods when needed.
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
string toLower(string str) {
transform(str.begin(), str.end(), str.begin(), ::tolower);
return str;
}
int main() {
string str1 = "Hello";
string str2 = "hello";
// Incorrect: Case-sensitive comparison
if (str1 == str2) {
cout << "The strings are equal." << endl;
} else {
cout << "The strings are not equal." << endl; // This will be printed
}
// Correct: Case-insensitive comparison
if (toLower(str1) == toLower(str2)) {
cout << "The strings are equal (case-insensitive)." << endl; // This will be printed
} else {
cout << "The strings are not equal (case-insensitive)." << endl;
}
return 0;
}
7.3. Ignoring Null Termination with strcmp()
- Problem: Assuming that
strcmp()
will work correctly with non-null-terminated character arrays. - Consequences:
strcmp()
might read beyond the allocated memory, leading to undefined behavior or crashes. - Solution: Ensure that C-style strings are always null-terminated.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[] = {'H', 'e', 'l', 'l', 'o'}; // Not null-terminated
char str2[] = {'H', 'e', 'l', 'l', 'o', ''}; // Null-terminated
// Incorrect: Using strcmp with a non-null-terminated string
// int result = strcmp(str1, "Hello"); // Can lead to undefined behavior
// Correct: Using strcmp with a null-terminated string
int result = strcmp(str2, "Hello");
if (result == 0) {
cout << "The strings are equal." << endl;
} else {
cout << "The strings are not equal." << endl;
}
return 0;
}
7.4. Overlooking Performance Implications
- Problem: Not considering the performance implications of different string comparison methods, especially in performance-critical applications.
- Consequences: Inefficient code that can lead to slow performance or high resource consumption.
- Solution: Benchmark different methods and choose the one that best fits your performance needs.
7.5. Failing to Handle Different Character Encodings
- Problem: Assuming that all strings are encoded in the same character set (e.g., ASCII or UTF-8).
- Consequences: Incorrect comparisons when dealing with strings in different encodings.
- Solution: Use appropriate encoding conversion techniques when comparing strings in different encodings.
7.6. Recommendations for Avoiding Mistakes
- Understand the Tools: Familiarize yourself with the behavior and limitations of different string comparison methods.
- Test Thoroughly: Test your string comparisons with various inputs to ensure they work correctly.
- Follow Best Practices: Adhere to best practices for string handling in C++, such as using
std::string
objects and ensuring null termination for C-style strings. - Document Your Code: Clearly document your string comparison logic, including whether it is case-sensitive or case-insensitive.
By being aware of these common mistakes and following the recommendations outlined above, you can write more robust and reliable string comparison code in C++.
8. Practical Applications and Use Cases
String comparison is a fundamental operation in many real-world applications. Understanding how to effectively compare strings is essential for developing robust and efficient software. This section explores various practical applications and use cases of string comparison in C++.
8.1. User Input Validation
- Description: Verifying that user inputs match expected formats or criteria.
- Example: Validating email addresses, phone numbers, or usernames.
#include <iostream>
#include <string>
#include <regex>
using namespace std;
bool isValidEmail(const string& email) {
const regex pattern(
"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
);
return regex_match(email, pattern);
}
int main() {
string email;
cout << "Enter your email address: ";
cin >> email;
if (isValidEmail(email)) {
cout << "Valid email address." << endl;
} else {
cout << "Invalid email address." << endl;
}
return 0;
}
8.2. Sorting Algorithms
- Description: Arranging lists of strings in a specific order, such as alphabetical or lexicographical.
- Example: Sorting a list of names or words.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<string> names = {"Charlie", "Alice", "Bob", "David"};
sort(names.begin(), names.end());
cout << "Sorted names:" << endl;
for (const string& name : names) {
cout << name << endl;
}
return 0;
}
8.3. Searching and Pattern Matching
- Description: Finding specific words, phrases, or patterns in larger texts.
- Example: Implementing a search function in a text editor or web application.
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "This is a sample text for searching.";
string keyword = "sample";
size_t found = text.find(keyword);
if (found != string::npos) {
cout << "Keyword found at position: " << found << endl;
} else {
cout << "Keyword not found." << endl;
}
return 0;
}
8.4. Authentication Systems
- Description: Verifying usernames and passwords against stored credentials.
- Example: Implementing a login system for a web application.
#include <iostream>
#include <string>
using namespace std;
int main() {
string username, password;
string storedUsername = "admin";
string storedPassword = "password123";
cout << "Enter your username: ";
cin >> username;
cout << "Enter your password: ";
cin >> password;
if (username == storedUsername && password == storedPassword) {
cout << "Login successful." << endl;
} else {
cout << "Login failed." << endl;
}
return 0;
}
8.5. Configuration File Parsing
- Description: Reading and interpreting settings from configuration files.
- Example: Parsing a configuration file to set application parameters.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <map>
using namespace std;
int main() {
ifstream configFile("config.txt");
string line;
map<string, string> config;
if (