笔记:C++学习之旅---IO库
笔记:C++学习之旅---IO库
C++的输入输出分为三种:
(1)基于控制台的I/O
(2)基于文件的I/O
(3)基于字符串的I/O
练习8.4 编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中,将每一行作为一个独立的元素存于vector中。
#include
<iostream>
#include
<vector>
#include
<string>
#include
<fstream>
using
namespace
std;
void
ReadFileToVec(
const
string
&
fileName
,
vector
<
string
> &
vec
)
{
ifstream
ifs(
fileName
);//从文件读取数据
if
(ifs)
{
string
buf;
while
(getline(ifs, buf))
vec
.push_back(buf);
}
}
int
main()
{
vector
<
string
> vec;
//ofstream fd;//向文件写入数据
///string message;
//fd.open("./book.txt");
//cout << "请输入一串字符存入book.txt(-1退出)" << endl;
//cin >> message;
//fd << message;
ReadFileToVec(
"./book.txt"
, vec);
for
(
const
auto
&str : vec)
cout << str << endl;
system(
"pause"
);
return
0;
}
使用istringstream
当我们的某些工作是对整行文本进行处理,而其他一些工作是处理行内的单个单词时,通常可以使用istringstream。
练习8.9 打印一个istringstream对象的内容
#include
<iostream>
#include
<sstream>
using
namespace
std;
istream
&func(
istream
&
is
)
{
string
buf;
while
(
is
>> buf)
{
cout << buf << endl;
}
is
.clear();
return
is
;
}
int
main()
{
istringstream
iss(
"hello"
);
func(iss);
return
0;
}
练习8.10 编写程序,将来自一个文件中的行保存在一个vector<string>中,然后使用一个istringstream从vector读取数据元素,每次读取一个单词。
#include
<iostream>
#include
<vector>
#include
<string>
#include
<sstream>
#include
<fstream>
using
namespace
std;
int
main()
{
ofstream
out;
out.open(
"./book.txt"
);
string
message;
cout <<
"请从键盘输入一串字符\n"
;
cin >>message;
out << message;
out.close();
ifstream
ifs(
"./book.txt"
);
if
(!ifs)
{
cerr <<
"No Data?"
<< endl;
return
-1;
}
vector
<
string
> vecline;
string
line;
while
(getline(ifs, line))
vecline.push_back(line);
for
(
auto
&s : vecline)
{
istringstream
iss(s);
string
word;
while
(iss >> word)
{
cout << word << endl;
}
}
ifs.close();
return
0;
}
使用ostringstream
当我们逐步构造输出,希望最后一起打印时,ostringstream是很有用的。例如,对于上一节的例子,我们可能想逐个验证电话号码并改变其格式。如果所有号码都是有效地,我们希望输出一个新的文件,包含改变格式后的号码。对于那些无效的号码,我们不会将它们输出到新文件中,而是打印一条包含人名和无效号码的错误信息。
练习8.13
重写本节的电话号码程序,从一个命名文件而非cin读取数据。

浙公网安备 33010602011771号