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;能够提供一…

springboot 事务管理

在Spring Boot中&#xff0c;事务管理是通过Spring框架的事务管理模块来实现的。Spring提供了声明式事务管理和编程式事务管理两种方式。通常&#xff0c;我们使用声明式事务管理&#xff0c;因为它更简洁且易于维护。 1. 声明式事务管理 声明式事务管理是通过注解来实现的。…

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文件来…

Leetcode 3448. Count Substrings Divisible By Last Digit

Leetcode 3448. Count Substrings Divisible By Last Digit 1. 解题思路2. 代码实现 题目链接&#xff1a;3448. Count Substrings Divisible By Last Digit 1. 解题思路 这一题的话我们走的是一个累积数组的思路。 首先&#xff0c;我们使用一个cache数组记录下任意段数字…

三维模拟-机械臂自翻车

机械仿真 前言效果图后续 前言 最近在研究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;商…

2月9日QT

优化登录框&#xff1a; 当用户点击取消按钮&#xff0c;弹出问题对话框&#xff0c;询问是否要确定退出登录&#xff0c;并提供两个按钮&#xff0c;yes|No&#xff0c;如果用户点击的Yes&#xff0c;则关闭对话框&#xff0c;如果用户点击的No&#xff0c;则继续登录 当用户…

安卓路由与aop 以及 Router-api

安卓路由&#xff08;Android Router&#xff09;和AOP&#xff08;面向切面编程&#xff09;是两个在Android开发中常用的概念。下面我将详细讲解这两个概念及其在Android开发中的应用。 一、安卓路由 安卓路由主要用于在应用程序中管理不同组件之间的导航和通信。它可以简化…

大模型赋能网络安全整体应用流程概述

一、四个阶段概述 安全大模型的应用大致可以分为四个阶段: 阶段一主要基于开源基础模型训练安全垂直领域的模型; 阶段二主要基于阶段一训练出来的安全大模型开展推理优化、蒸馏等工序,从而打造出不同安全场景的专家模型,比如数据安全领域、安全运营领域、调用邮件识别领…

nexus部署及配置https访问

1. 使用docker-compose部署nexus docker-compose-nexus.yml version: "3" services:nexus:container_name: my-nexusimage: sonatype/nexus3:3.67.1hostname: my-nexusnetwork_mode: hostports:- 8081:8081deploy:resources:limits:cpus: 4memory: 8192Mreservations…

史上最快 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…

Docker从入门到精通- 容器化技术全解析

第一章&#xff1a;Docker 入门 一、什么是 Docker&#xff1f; Docker 就像一个超级厉害的 “打包神器”。它能帮咱们把应用程序和它运行所需要的东东都整整齐齐地打包到一起&#xff0c;形成一个独立的小盒子&#xff0c;这个小盒子在 Docker 里叫容器。以前呢&#xff0c;…

ProcessingP5js数据可视化

折线图绘制程序设计说明 可以读取表格数据&#xff0c;并转换成折线图&#xff0c;条形图和饼状图&#xff0c;并设计了衔接动画效果 1. 功能概述 本程序使用 Processing 读取 CSV 文件数据&#xff0c;并绘制带有坐标轴和数据点的折线图。横坐标&#xff08;X 轴&#xff09…

使用云计算,企业的数据监管合规问题如何解决?

使用云计算&#xff0c;企业的数据监管合规问题如何解决&#xff1f; 在当今这个信息化、数字化的时代&#xff0c;数据无疑成为了企业最宝贵的资产之一。随着云计算的普及&#xff0c;企业将大量数据存储在云端&#xff0c;不仅提升了效率&#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_…