C++primer:string流
2015-10-01 15:48
387 查看
string流分为istringstream和ostringstream,它们负责绑定一个string对象.
[1]练习:从一个文件里读取一行,然后读取单词分别输出.
void func(string filename) { S vec; string word, line; ifstream record(filename);//读一个文件 if (record)//打开成功 { while (getline(record,line))//读取一行 { istringstream is(line); while (is>>word) cout << word<<endl; } } }
[2]
如果需要将新的string值拷贝到一个流中,最好先用s.clear()清空流的状态.
void func(string filename) { S vec; string word, line; istringstream is(line);//将该流定义在循环的外部 ifstream record(filename);//读一个文件 if (record)//打开成功 { while (getline(record,line))//读取一行 { is.clear();//清空 is.str(line);//拷贝 while (is>>word) cout << word<<endl; } } }
[3]电话号码程序:从一个文件读入一些人和他们的电话号码,一个人有一个或者多个电话号码.
void func(string filename,P & person)//电话本程序 { string word, line,name; ifstream record(filename);//读一个文件 if (record)//打开成功 { while (getline(record,line))//读取一行 name: tel1,tel2 .... { Personinfo temp; istringstream is(line); is >> temp.name; while (is >> word) temp.phone.push_back(word); person.push_back(temp); } } }
[4]ostringstream流的练习:通过ostringstream流实现对输出的控制。检查电话号码是否有误,直到所有号码无误再将一个人的信息输出.
void func(string filename,P & person)//电话本程序 { string word, line,name; ifstream record(filename);//读一个文件 if (record)//打开成功 { while (getline(record,line))//读取一行 name: tel1,tel2 .... { Personinfo temp; istringstream is(line); is >> temp.name; while (is >> word) temp.phone.push_back(word); person.push_back(temp); } } }
bool valid(const string& s)//判断号码是否正确
{
for (auto it : s)
{
if (!isdigit(it))
return false;
}
return true;
}
string format(const string& str)//处理号码格式
{
return str.substr(0, 3) + "-" + str.substr(3, 3) + "-" + str.substr(6);
}
int main(int argc, char** argv)
{
P people;
func(argv[1], people);//从文件读取号码
for (const auto &entry : people)
{
ostringstream formatted, badNums;
for (const auto &nums : entry.phone)
{
if (!valid(nums))
badNums << " " << nums;
else
formatted << " " << format(nums);
}
if (badNums.str().empty())//没有错误的数
cout << entry.name << " " << formatted.str() << endl;
else//有错误的数
cout << "input error: " << entry.name << " invalid number(s)" << badNums.str() << endl;
}
return 0;
}
相关文章推荐
- C++中的Static关键字
- 黑马程序员---C语言学习笔记之预处理指令、宏和条件编译
- c/c++: uint8_t uint16_t uint32_t uint64_t size_t ssize_t数据类型
- c语言知识点复习
- C++中new和malloc的区别
- 递归求解1~9组成的特殊9位整数
- C++类包含问题(重复包含和相互包含)
- 黑马程序员——OC语言基础---对象和方法
- Java jna学习之----VC++2010创建并调用动态链接库dll
- 截木棍(最大公约数)
- 我的第一个C++程序
- C++ Struct
- 深入理解C++三大特性之一 ——多态
- 【学习笔记】C语言 随机数的生成原理分析和各类随机数公式
- C语言实现的猜数字小游戏(主要是对于自定义函数的运用)
- C语言实现的猜数字小游戏(主要是对于自定义函数的运用)
- [c++]无锁队列
- C/C++ Volatile关键词深度剖析(转)
- 《C++primer(第五版)》学习之路-第十三章:拷贝控制
- 字符串匹配——C++使用Regex