您的位置:首页 > 其它

17.5节练习

2016-07-07 20:27 267 查看
练习17.5.34 编写一个程序,展示如何使用表17.17和表17.18中的每个操作符。

#include <iostream>
using namespace std;
int main()
{
int val = 10;
float val2 = 10.0;
bool bool_val = val;

cout << boolalpha << bool_val << noboolalpha << endl;
cout << showbase << val << endl;
cout << hex << val << endl;
cout << oct << val << noshowbase << endl;
cout << val2 << endl;
cout << showpoint << val2 << noshowpoint << endl;
cout << showpos << val << noshowpos << endl;	//并没有显示+
cout << uppercase << showbase << hex << 1212422424241 << nouppercase << noshowbase << endl;
//...
}


练习17.35 修改第670页中的程序,打印2的平方根,但这次打印十六进制数字的大写形式。

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << uppercase << showbase << hexfloat << sqrt(2) << endl;
cout << nouppercase << noshowbase;
}


练习17.36 修改上一题中的程序,打印不同的浮点数,使它们排成一列。

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{

cout << setw(12) << left << 100 << endl;
cout << setw(12) << right << 100 << setfill(' ') << endl;
cout << setw(12) << -3 << endl;
cout << setw(12) << internal << -3 << endl;
cout << setw(12) << setfill('*') << hexfloat << 15.0 << defaultfloat << endl;
cout << setw(12) << 100 << endl;
}


练习17.37 用未格式化版本的getline逐行读取一个文件。测试你的程序,给它一个文件,既包含空行又包含长度超过你传递给getline的字符数组大小的行。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream in("17.37.txt");
string line;
while (getline(in, line)) {
cout << line << endl;
}
in.close();
cout << endl;

fstream in2("17.37.txt");
char ch[100];
while (in2) {
in2.getline(ch, 10);
cout << ch << endl;
}
in2.close();
}


练习17.38 扩展上一题中你的程序,将读入的每个单词打印到它所在的行。

#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
int main()
{
fstream in("17.37.txt");
char ch;
while (in.get(ch)) {
cout.put(ch);
}
cout << endl;
}


练习17.39 对本节给出的seek程序,编写你自己的版本。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()

{
fstream inOut("17.39.txt", fstream::ate);
if (inOut) {
cerr << "Unable to open file!" << endl;
return EXIT_FAILURE;
}
fstream::pos_type end_mark = inOut
4000
.tellg();
inOut.seekg(0, fstream::beg);
size_t cnt = 0;
string line;
while (inOut && inOut.tellg() != end_mark && getline(inOut, line)) {
cnt += line.size() + 1;
auto mark = inOut.tellg();
inOut.seekp(0, fstream::end);
inOut << cnt;
if (mark != end_mark) {
inOut << " ";
}
inOut.seekg(mark);
}
inOut.seekp(0, fstream::end);
inOut << "\n";
inOut.close();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: