Practical Conversion Examples
Conversion Scenarios
Stringstream provides powerful type conversion capabilities across different data types.
String to Numeric Conversions
String to Integer
std::string str = "42";
std::stringstream ss(str);
int number;
ss >> number; // number = 42
String to Double
std::string str = "3.14159";
std::stringstream ss(str);
double value;
ss >> value; // value = 3.14159
Numeric to String Conversions
Integer to String
std::stringstream ss;
int number = 123;
ss << number;
std::string str = ss.str(); // str = "123"
Multiple Type Conversion
std::stringstream ss;
int age = 30;
double height = 1.75;
std::string name = "John";
ss << "Name: " << name
<< ", Age: " << age
<< ", Height: " << height;
std::string result = ss.str();
Complex Conversion Workflow
graph TD
A[Input String] --> B[Stringstream]
B --> C{Parse/Convert}
C --> D[Multiple Data Types]
D --> E[Processed Output]
Conversion Techniques
Technique |
Input |
Output |
Example |
String to Int |
"123" |
Integer |
123 |
String to Float |
"3.14" |
Float |
3.14 |
Int to String |
42 |
"42" |
Conversion |
Safe Conversion Practices
bool safeConvert(const std::string& input, int& result) {
std::stringstream ss(input);
return !!(ss >> result);
}
int main() {
std::string str = "456";
int number;
if (safeConvert(str, number)) {
std::cout << "Converted: " << number << std::endl;
} else {
std::cout << "Conversion failed" << std::endl;
}
return 0;
}
Parsing Complex Data Structures
struct Person {
std::string name;
int age;
double salary;
};
Person parsePerson(const std::string& data) {
std::stringstream ss(data);
Person p;
std::getline(ss, p.name, ',');
ss >> p.age;
ss.ignore(); // Skip comma
ss >> p.salary;
return p;
}
int main() {
std::string personData = "John Doe,35,50000.50";
Person person = parsePerson(personData);
}
Advanced Conversion Scenarios
CSV Parsing
std::vector<std::string> splitCSV(const std::string& line) {
std::vector<std::string> result;
std::stringstream ss(line);
std::string item;
while (std::getline(ss, item, ',')) {
result.push_back(item);
}
return result;
}
Error Handling in Conversions
bool validateConversion(const std::string& input) {
std::stringstream ss(input);
int value;
// Check if conversion is possible
return (ss >> value) && ss.eof();
}
Explore more advanced C++ techniques with LabEx's interactive programming environments!