字符串与输出
Coddy 面向 Ruby 开发者的 C++ 课程的第 2 课,共 48 课。
Ruby 的 String 是一种可变对象,带有编码,因此 length 统计字符数,而 bytesize 统计字节数。C++ 的 std::string 持有可变字节序列;流插入会格式化值。长度统计的是字节数,而不是 Unicode 字符数。
Ruby
word = "café"
puts word.length
puts word.bytesize
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::string name="oak";std::cout<<name.size()<<"\n";
}
分别跟踪每个程序。这些示例通过使用与任务不同的操作或数据来展示这个概念;不假定源代码和目标代码的输出一致。
挑战
简单输入:一行名字,可以为空。返回 Hello, NAME!,保留空格。
在 exercise.hpp 和 exercise.cpp 中实现已声明的 API。两个文件都可以编辑;请保留公共签名。已锁定的 main.cpp 会读取标准输入并直接调用 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<<greet(rows.empty()?"":rows[0])<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C++中的所有课
自己练习: C++ 在线编译器