Menu
CoddyTech

Streams and Exact Parsing

Lesson 27 of 48 in Coddy's C++ for Lua Developers course.

Lua's tonumber never raises: it returns nil for text that is not a number, such as "7x", and it accepts surrounding spaces, hexadecimal like "0x10" and floats. Splitting is done with patterns such as %S+. C++ stream extraction with >> reads as much as it can and reports success through the stream state: "7x" extracts 7 and leaves x for the next read, and a failed extraction sets the fail state and stores 0. Check the stream after each read, and when the contract requires exact input, also reject trailing tokens.

Lua

local word, number = ("oak 7"):match("^(%S+)%s+(%S+)$")
print(word .. "/" .. tonumber(number))
print(tonumber("7x"))
print(tonumber(" 8 ") + 1)

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
std::istringstream in("oak 7x");
std::string word;int n;
if(in>>word>>n)std::cout<<word<<"/"<<n<<"\n";
std::string rest;
if(in>>rest)std::cout<<"trailing "<<rest<<"\n";
std::istringstream bad("x9");
int m=5;
if(!(bad>>m))std::cout<<"failed "<<m<<"\n";
}

Where Lua code writes local n = tonumber(s); if not n then ... end, the C++ port tests the stream and then checks that nothing is left over.

challenge icon

Challenge

Easy

Input: one line that should contain exactly two integers and no other tokens. Return their sum as text, or invalid. Leading/trailing spaces allowed.

Implement the declared API in exercise.hpp and exercise.cpp. Both files are editable; preserve the public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::cout<<sum_pair(rows.empty()?"":rows[0])<<"\n";
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C++ for Lua Developers

Practice on your own: Online C++ compiler