字符串与输出
Coddy 面向 Rust 开发者的 C++ 课程的第 2 课,共 48 课。
Rust 将拥有所有权的 String 与借用的 str 区分开,并强制使用 UTF-8。C++ 字符串不保证自动符合 UTF-8。C++ std::string 拥有可变字节序列;流插入会对值进行格式化。长度统计的是字节数,而不是 Unicode 字符数。
Rust
fn main(){
println!("{}", "oak".len());
}
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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 C++中的所有课
自己练习: C++ 在线编译器