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.pswp.cn/news/895148.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/895148.shtml
英文地址,請注明出處:http://en.pswp.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_…