流与精确解析
Coddy 面向 Ruby 开发者的 C++ 课程的第 27 课,共 48 课。
Ruby 提供了两种转换方式:Integer(text) 会引发 ArgumentError,除非整个字符串都是数字(或者在使用 exception: false 时返回 nil);而 String#to_i 会读取开头的数字前缀,如果没有数字,则静默返回 0。C++ 流会在流状态中表示提取失败,而且和 to_i 一样,>> 遇到第一个不能属于数字的字符时就会停止。C++ 流提取会通过流状态报告是否成功。如果契约要求输入必须完全匹配,请验证转换结果,并拒绝意外的尾随标记。
Ruby
word, number = "oak 7".split
puts "#{word}/#{Integer(number)}"
p "12px".to_i
p Integer("12px", exception: false)
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 7");std::string word;int n;if(in>>word>>n)std::cout<<word<<"/"<<n<<"\n";
std::istringstream bad("12px");int m=0;std::string rest;if(bad>>m&&!(bad>>rest))std::cout<<"exact\n";else std::cout<<"rejected "<<m<<"\n";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来展示这个概念,不保证源程序和目标程序的输出一致。
挑战
简单输入:一行内容,其中应恰好包含两个整数,且不能包含其他标记。返回它们的和,格式为文本;否则返回 invalid。允许有前导或尾随空格。
在 exercise.hpp 和 exercise.cpp 中实现已声明的 API。这两个文件都可以编辑;请保留公共签名。锁定的 main.cpp 会读取 stdin 并直接调用 API。题目有说明时,它还会独立检查公共 API 的行为。在 API 中返回值,不要打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C++中的所有课
自己练习: C++ 在线编译器