Basic String Output
Standard Output Methods
C++ provides multiple ways to output strings, with the most common methods being:
1. Using std::cout
#include <iostream>
#include <string>
int main() {
std::string message = "Hello, LabEx!";
std::cout << message << std::endl;
return 0;
}
2. Using printf()
#include <cstdio>
#include <string>
int main() {
std::string text = "C++ String Output";
printf("%s\n", text.c_str());
return 0;
}
Output Stream Manipulators
Manipulator |
Description |
Example |
std::endl |
Adds newline and flushes buffer |
std::cout << message << std::endl; |
\n |
Adds newline without flushing |
std::cout << message << "\n"; |
graph TD
A[String Output] --> B{Formatting Options}
B --> C[Width]
B --> D[Alignment]
B --> E[Precision]
Width and Alignment
#include <iostream>
#include <iomanip>
#include <string>
int main() {
std::string name = "LabEx";
// Right-aligned, width 10
std::cout << std::right << std::setw(10) << name << std::endl;
// Left-aligned, width 10
std::cout << std::left << std::setw(10) << name << std::endl;
return 0;
}
Multiple String Output
#include <iostream>
#include <string>
int main() {
std::string first = "Hello";
std::string second = "World";
// Concatenated output
std::cout << first << " " << second << std::endl;
return 0;
}
Error Output
#include <iostream>
#include <string>
int main() {
std::string error_msg = "An error occurred!";
// Output to standard error stream
std::cerr << error_msg << std::endl;
return 0;
}
std::cout
is generally slower than printf()
- Use
std::ios::sync_with_stdio(false)
to improve performance
- Avoid frequent output in performance-critical sections
Best Practices
- Use
std::cout
for most string outputs
- Prefer
std::endl
for debugging
- Use
\n
for performance-critical code
- Utilize stream manipulators for formatting
Complete Example
#include <iostream>
#include <iomanip>
#include <string>
int main() {
std::string product = "LabEx Course";
double price = 49.99;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Product: " << std::setw(15) << product
<< " Price: $" << price << std::endl;
return 0;
}
By mastering these string output techniques, you'll be able to effectively display and format strings in your C++ programs.