cs106x-lecture3(Autumn 2017)

打卡cs106x(Autumn 2017)-lecture3

1、streamErrors 

Suppose an input file named streamErrors-data.txt contains the following text:

Donald Knuth
M
76
Stanford U.

The code below attempts to read the data from the file, but each section has a bug. Correct the code and submit a version that reads the code and prints the values expected as indicated in the comments.

ifstream input;
input.open("streamErrors-data.txt");string name;
name = input.getline();      // #1   "Donald Knuth"
cout << name << endl;char gender;
gender = input.get();        // #2   'M'
cout << gender << endl;int age;
getline(input, age);
stringToInteger(age);        // #3   76
cout << age << endl;string jobtitle;
input >> jobtitle;           // #4   "Stanford U."
cout << jobtitle << endl;

解答:

#include <iostream>
#include <fstream>
#include <string>
#include "console.h"
#include "strlib.h"using namespace std;int main() {ifstream input;input.open("streamErrors-data.txt");string name;// getline的使用方法应为getline(f&, s&)getline(input, name);      // #1   "Donald Knuth"cout << name << endl;char gender;// get()读取的是单个chargender = input.get();        // #2   'M'cout << gender << endl;input.get();string age; // 使用getline(f&, s&)的s是string类型getline(input, age);// cout << age << endl; 根据输出额外的空行得知,#2还有换行符未读取stringToInteger(age);        // #3   76cout << age << endl;string jobtitle;// >> 读取以空格为间隔while(input >> jobtitle) {           // #4   "Stanford U."cout << jobtitle << " ";}cout << endl;return 0;
}

2、inputStats

Write a function named inputStats that accepts a string parameter representing a file name, then opens/reads that file's contents and prints information to the console about the file's lines. Report the length of each line, the number of lines in the file, the length of the longest line, and the average characters per line, in exactly the format shown below. You may assume that the input file contains at least one line of input. For example, if the input file carroll.txt contains the following data:

Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,Beware the JubJub bird and shun
the frumious bandersnatch.

Then the call of inputStats("carroll.txt"); should produce the following console output:

Line 1 has 30 chars
Line 2 has 41 chars
Line 3 has 0 chars
Line 4 has 31 chars
Line 5 has 26 chars
5 lines; longest = 41, average = 25.6

If the input file does not exist or is not readable, your function should print no output. If the file does exist, you may assume that the file contains at least 1 line of input.

Constraints: Your solution should read the file only once, not make multiple passes over the file data.

解答:

#include <iostream>
#include <fstream>
#include <string>
#include "console.h"
using namespace std;void inputStats(string filename);int main() {string filename = "carroll.txt";inputStats(filename);return 0;
}void inputStats(string filename) {ifstream input;input.open(filename);if (input.is_open()) {int totalLength = 0;int numLine = 0;int len;int longest = 0;string line = "";while (getline(input, line)) {numLine++;len = line.length();if (len > longest) {longest = len;}cout << "Line " << numLine << " has " << len << " chars" << endl;totalLength += len;}double avg = totalLength / double(numLine);cout << numLine << " lines; longest = " << longest << ", average = " << avg;}input.close();
}

3、hoursWorked 

Write a function named hoursWorked that accepts as a parameter a string representing an input file name of section leader data and computes and prints a report of how many hours each section leader worked. Each line of the file is in the following format, where each line begins with an employee ID, followed by an employee first name, and then a sequence of tokens representing hours worked each day. Suppose the input file named hours.txt and contains the following lines:

123 Alex 3 2 4 1
46 Jessica 8.5 1.5 5 5 10 6
7289 Erik 3 6 4 4.68 4

For the above input file, the call of hoursWorked("hours.txt"); would produce the following output.

Alex     (ID#  123) worked 10.0 hours (2.50/day)
Jessica  (ID#   46) worked 36.0 hours (6.00/day)
Erik     (ID# 7289) worked 21.7 hours (4.34/day)

Match the format exactly, including spacing. The names are in a left-aligned 9-space-wide field; the IDs are in a right-aligned 4-space-wide field; the total hours worked should show exactly 1 digit after the decimal; and the hours/day should have exactly 2 digits after the decimal. Consider using functions of the iomanip library to help you.

解答:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
#include "console.h"
#include "strlib.h"using namespace std;void hoursWorked(string filename);int main() {string filename = "hours.txt";hoursWorked(filename);return 0;
}void hoursWorked(string filename) {ifstream input;input.open(filename);// 是否能打开文件if (input.is_open()) {string line;// 循环按行获取数据while (getline(input, line)) {istringstream input2(line);string id;string name;int day = 0;double dayWorked;double totalWorked = 0;// 每行的数据获取input2 >> id;input2 >> name;while (input2 >> dayWorked) {totalWorked += dayWorked;day++;}// 按行格式化输出cout << name;cout << setfill(' ') << setw(9 - name.length() + 5) << "(ID# ";cout << setfill(' ') << setw(4) << id;cout << ") worked " << fixed << setprecision(1) << totalWorked;cout << " hours (" << fixed << setprecision(2) << totalWorked / day;cout << "/day)" << endl;}}input.close();
}

4、gridMystery

What is the grid state after the following code?

Grid<int> g(4, 3);
for (int r = 0; r < g.numRows(); r++) {       // {{1, 2, 3},for (int c = 0; c < g.numCols(); c++) {   //  {1, 2, 3},g[r][c] = c + 1;                      //  {1, 2, 3},}                                         //  {1, 2, 3}}
}for (int c = 0; c < g.numCols(); c++) {for (int r = 1; r < g.numRows(); r++) {g[r][c] += g[r - 1][c];}
}

解答:

{{1, 2, 3}, {2, 4, 6}, {3, 6, 9}, {4, 8, 12}}

5、knightCanMove

Write a function named knightCanMove that accepts a reference to a Grid of strings and two row/column pairs (r1, c1), (r2, c2) as parameters, and returns true if there is a knight at chess board square (r1, c1) and he can legally move to empty square (r2, c2). For your function to return true, there must be a knight at square (r1, c1), and the square at (r2, c2) must store an empty string, and both locations must be within the bounds of the grid.

Recall that a knight makes an "L" shaped move, going 2 squares in one dimension and 1 square in the other. For example, if the board looks as shown below and the board square at (1, 2) stores "knight", then the call of knightCanMove(board, 1, 2, 2, 4) returns true.

r\c01234567
0"""""""""king"""""""
1"""""knight"""""""""""
2""""""""""""""""
3"""rook"""""""""""""
4""""""""""""""""
5""""""""""""""""
6""""""""""""""""
7""""""""""""""""

 

解答:

bool knightCanMove(Grid<string> g, int r1, int c1, int r2, int c2) {if (g.inBounds(r1, c1) && g.inBounds(r2, c2)) { // 是否在有效范围内if (g[r1][c1] == "knight" && g[r2][c2] =="") { // 值是否正确// 移动方式是否正确bool canMove1 = (abs(r1 - r2) == 2 && abs(c1 - c2) == 1);bool canMove2 = (abs(r1 - r2) == 1 && abs(c1 - c2) == 2);if (canMove1 || canMove2) {return true;}}}return false;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/895148.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++模板编程——typelist的实现

文章最后给出了汇总的代码&#xff0c;可直接运行 1. typelist是什么 typelist是一种用来操作类型的容器。和我们所熟知的vector、list、deque类似&#xff0c;只不过typelist存储的不是变量&#xff0c;而是类型。 typelist简单来说就是一个类型容器&#xff0c;能够提供一…

windows通过网络向Ubuntu发送文件/目录

由于最近要使用树莓派进行一些代码练习&#xff0c;但是好多东西都在windows里或虚拟机上&#xff0c;就想将文件传输到树莓派上&#xff0c;但试了发现u盘不能简单传送&#xff0c;就在网络上找到了通过windows 的scp命令传送 前提是树莓派先开启ssh服务&#xff0c;且Window…

字节跳动后端一面

&#x1f4cd;1. Gzip压缩技术详解 Gzip是一种流行的无损数据压缩格式&#xff0c;它使用DEFLATE算法来减少文件大小&#xff0c;广泛应用于网络传输和文件存储中以提高效率。 &#x1f680; 使用场景&#xff1a; • 网站优化&#xff1a;通过压缩HTML、CSS、JavaScript文件来…

三维模拟-机械臂自翻车

机械仿真 前言效果图后续 前言 最近在研究Unity机械仿真&#xff0c;用Unity实现其运动学仿真展示的功能&#xff0c;发现一个好用的插件“MGS-Machinery-master”&#xff0c;完美的解决了Unity关节定义缺少液压缸伸缩关节功能&#xff0c;内置了多个场景&#xff0c;讲真的&…

USB子系统学习(四)用户态下使用libusb读取鼠标数据

文章目录 1、声明2、HID协议2.1、描述符2.2、鼠标数据格式 3、应用程序4、编译应用程序5、测试6、其它 1、声明 本文是在学习韦东山《驱动大全》USB子系统时&#xff0c;为梳理知识点和自己回看而记录&#xff0c;全部内容高度复制粘贴。 韦老师的《驱动大全》&#xff1a;商…

史上最快 Python版本 Python 3.13 安装教程

Python3.13安装和配置 一、Python的下载 1. 网盘下载地址 (下载速度比较快&#xff0c;推荐&#xff09; Python3.13.0下载&#xff1a;Python3.13.0下载地址&#xff08;windows&#xff09;3.13.0下载地址&#xff08;windows&#xff09; 点击下面的下载链接&#xff0c…

AWS Fargate

AWS Fargate 是一个由 Amazon Web Services (AWS) 提供的无服务器容器计算引擎。它使开发者能够运行容器化应用程序&#xff0c;而无需管理底层的服务器或虚拟机。简而言之&#xff0c;AWS Fargate 让你只需关注应用的容器本身&#xff0c;而不需要管理运行容器的基础设施&…

vue3+vite+eslint|prettier+elementplus+国际化+axios封装+pinia

文章目录 vue3 vite 创建项目如果创建项目选了 eslint prettier从零教你使用 eslint prettier第一步&#xff0c;下载eslint第二步&#xff0c;创建eslint配置文件&#xff0c;并下载好其他插件第三步&#xff1a;安装 prettier安装后配置 eslint (2025/2/7 补充) 第四步&am…

vLLM V1 重磅升级:核心架构全面革新

本文主要是 翻译简化个人评读&#xff0c;原文请参考&#xff1a;vLLM V1: A Major Upgrade to vLLM’s Core Architecture vLLM V1 开发背景 2025年1月27日&#xff0c;vLLM 开发团队推出 vLLM V1 alpha 版本&#xff0c;这是对框架核心架构的里程碑式升级。基于过去一年半的…

Jupyter Notebook自动保存失败等问题的解决

一、未生成配置文件 需要在命令行中&#xff0c;执行下面的命令自动生成配置文件 jupyter notebook --generate-config 执行后会在 C:\Users\用户名\.jupyter目录中生成文件 jupyter_notebook_config.py 二、在网页端打开Jupyter Notebook后文件保存失败&#xff1b;运行代码…

使用wpa_supplicant和wpa_cli 扫描wifi热点及配网

一&#xff1a;简要说明 交叉编译wpa_supplicant工具后会有wpa_supplicant和wpa_cli两个程序生产&#xff0c;如果知道需要连接的wifi热点及密码的话不需要遍历及查询所有wifi热点的名字及信号强度等信息的话&#xff0c;使用wpa_supplicant即可&#xff0c;否则还需要使用wpa_…

【真一键部署脚本】——一键部署deepseek

目录 deepseek一键部署脚本说明 0 必要前提 1 使用方法 1.1 使用默认安装配置 1.1 .1 使用其它ds模型 1.2 使用自定义安装 2 附录&#xff1a;deepseek模型手动下载 3 脚本下载地址 deepseek一键部署脚本说明 0 必要前提 linux环境 python>3.10 1 使用方法 1.1 …

5.2Internet及其作用

5.2.1Internet概述 Internet称为互联网&#xff0c;又称英特网&#xff0c;始于1969年的美国ARPANET&#xff08;阿帕网&#xff09;&#xff0c;是全球性的网络。 互连网指的是两个或多个不同类型的网络通过路由器等网络设备连接起来&#xff0c;形成一个更大的网络结构。互连…

“图像识别分割算法:解锁视觉智能的关键技术

嘿&#xff0c;各位朋友&#xff01;今天咱们来聊聊图像识别分割算法。这可是计算机视觉领域里特别厉害的一项技术&#xff0c;简单来说&#xff0c;它能让机器“看懂”图像中的不同部分&#xff0c;并把它们精准地分出来。想象一下&#xff0c;机器不仅能识别出图里有猫还是狗…

AJAX项目——数据管理平台

黑马程序员视频地址&#xff1a; 黑马程序员——数据管理平台 前言 功能&#xff1a; 1.登录和权限判断 2.查看文章内容列表&#xff08;筛选&#xff0c;分页&#xff09; 3.编辑文章&#xff08;数据回显&#xff09; 4.删除文章 5.发布文章&#xff08;图片上传&#xff0…

html转PDF文件最完美的方案(wkhtmltopdf)

目录 需求 一、方案调研 二、wkhtmltopdf使用 如何使用 文档简要说明 三、后端服务 四、前端服务 往期回顾 需求 最近在做报表类的统计项目&#xff0c;其中有很多指标需要汇总&#xff0c;网页内容有大量的echart图表&#xff0c;做成一个网页去浏览&#xff0c;同时…

示例:JAVA调用deepseek

近日&#xff0c;国产AI DeepSeek在中国、美国的科技圈受到广泛关注&#xff0c;甚至被认为是大模型行业的最大“黑马”。在外网&#xff0c;DeepSeek被不少人称为“神秘的东方力量”。1月27日&#xff0c;DeepSeek应用登顶苹果美国地区应用商店免费APP下载排行榜&#xff0c;在…

.NET周刊【2月第1期 2025-02-02】

国内文章 dotnet 9 已知问题 默认开启 CET 导致进程崩溃 https://www.cnblogs.com/lindexi/p/18700406 本文记录 dotnet 9 的一个已知且当前已修问题。默认开启 CET 导致一些模块执行时触发崩溃。 dotnet 使用 ColorCode 做代码着色器 https://www.cnblogs.com/lindexi/p/…

AES200物理机部署DeepSeek-R1蒸馏模型

AES200物理机部署DeepSeek-R1模型 华为官方官宣自己的NPU支持DeepSeek-R1模型部署&#xff0c;华为的大模型推理部署依托于其大模型推理引擎&#xff1a;MindIE&#xff0c;但是根据MindIE的文档&#xff0c;其只支持以下硬件&#xff1a; 表1 MindIE支持的硬件列表 类型配置…

【后端开发】系统设计101——Devops,Git与CICD,云服务与云原生,Linux,安全性,案例研究(30张图详解)

【后端开发】系统设计101——Devops&#xff0c;Git与CICD&#xff0c;云服务与云原生&#xff0c;Linux&#xff0c;安全性&#xff0c;案例研究&#xff08;30张图详解&#xff09; 文章目录 1、DevopsDevOps与SRE与平台工程的区别是什么&#xff1f;什么是k8s&#xff08;Ku…