17.1
方法一:采用peek方法(注意该方法只读取下一个字符但不抽取)
//main.cpp
#include <iostream>
int main()
{
using namespace std;
cout << "enter your string to count<$ for end> :\n";
int count = 0;
int i = 0;
char ch;
char str[20];//存放$之前的字符
char next[20];//存放$及其后面的字符
while ((ch=cin.peek())!='$')//只能查看下一个字符
{
count++;
cin.get(str[i++]);//抽取字符否则peek将永远为第一个字符
}
str[i] = '\0';//使str成为一个字符串便于输出
cout <<"string befor $ "<< str
<<" include "<<count<<" characters.\n";
cin.getline(next, 20);
cout << "string after $: " << next;
return 0;
}
方法二:采用整行输入的get方法(不抽取分界符)
//main.cpp
#include <iostream>
#include<string>
int main()
{
using namespace std;
cout << "enter your string to count<$ for end> :\n";
char str[20];
string next;
cin.get(str, 20, '$');
getline(cin, next);
cout << "string befor $: " << str << endl;
cout << "next string: " << next << endl;
return 0;
}
17.2
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
int main(int argc, char *argv[])
{
using namespace std;
if (argc == 1)
{
cerr << "no file assign .\n";
exit(EXIT_FAILURE);
}
ofstream fout;
for (int i = 1; i < argc; i++)
{
fout.open(argv[i]);
if (!fout.is_open())
{
cout << "Could not open " << argv[i] << endl;
fout.clear();
continue;
}
cout << "enter your characters to file<EOF to quit> " << argv[i] << endl;
char ch;
while ((ch=cin.get())!=EOF)
{
fout << ch;
}
fout.clear();
fout.close();
ifstream fin(argv[i]);
string str;
getline(fin, str);
cout << "your string in file " << argv[i] << ": "
<< str<<endl;
fin.close();
}
return 0;
}
Windows执行步骤:1)在编译环境下执行生成exe可执行文件 ,在提示框中查看文件路径
2)打开cmd(windows10系统下搜索即可)
3)在cmd中输入文件路径以及所需的文件即可
注意事项:1)可执行文件路径一定要输入正确,不用管cmd命令框中默认的文件路径,直接重新输入即可(找到文件复制路径)
2)输入的命令为:路径/可执行文件名.exe 文件名;可执行文件一定要加后缀
3)如果需要处理的文件不存在,将自动创建一个新的文件,若需要文件为txt格式,必须在输入的文件名后加.txt后缀
17.3
//在命令窗口运行前至少需要创建argv[2]文件,并存入数据
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
int main(int argc, char *argv[])
{
using namespace std;
if (argc == 1)
{
cerr << "no file assign .\n";
exit(EXIT_FAILURE);
}
ofstream fout(argv[1]);//argv[1]为输入的第一个文件名其内容将被argv[2]覆盖
if (!fout.is_open())
{
cerr << argv[1] << " Could not open.\n";
fout.clear();
exit(EXIT_FAILURE);
}
ifstream fin(argv[2]);
if (!fin.is_open())
{
cerr << argv[2] << " Could not open.\n";
fin.clear();
exit(EXIT_FAILURE);
}
char ch;
while ((ch=fin.get())!=EOF)//读取argv[2]中数据
{
fout << ch;//将argv[2]中数据输出到argv[1]
}
fout.close();
fin.close();
cout << &#