CodeBlanks Logo Icon CodeBlanks

Summary - Advanced strings

Combine stringstream, stoi and to_string to write a CSV parser.

Summary: Parse a CSV line

In this summary we will combine istringstream, stoi and to_string to parse a CSV line. CSV separates values with commas; for example, "Alex,25,90" holds a name, age and grade.

The plan is: first use getline on an istringstream to read up to the comma, then pull the remaining two values with >>. Convert numbers with stoi, and fold the result into text with to_string. This combines different string operations in a single task.

Practice Read name and age from a CSV line

Add the #include <sstream> header. Define istringstream iss("Alex,25");. Declare string name; and int age;. Read the name up to the comma with getline(iss, name, ',');; pull the remaining integer with iss >> age;. Print with cout << name << " - " << age << endl;.

Starter code

main.cpp
#include <iostream>
#include <string>
// add the sstream header
using namespace std;

int main() {
    // define istringstream, read name with getline, pull age with >>, print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    istringstream iss("Alex,25");
    string name;
    int age;
    getline(iss, name, ',');
    iss >> age;
    cout << name << " - " << age << endl;
    return 0;
}

Expected output

Alex - 25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does getline(iss, name, ',') do?

  • Reads the whole line into one string
  • Reads from the stream up to a comma Correct answer
  • Converts a number to an integer
  • Inserts a piece into a string

Explanation: The third parameter is the delimiter; getline reads up to the comma.

2 Match each function with its job

Term Meaning
istringstream Turns string into a stream
getline Reads up to a delimiter
stoi Converts to integer
to_string Converts to string

3 Fill in the blank: getline call

Question
istringstream iss("Alex,30");
string name;
____(iss, name, ',');
Answer
istringstream iss("Alex,30");
string name;
getline(iss, name, ',');

Explanation: getline reads from the stream up to the comma.

All lessons in Beginner