从文件中读取和显示字符串
reading and displaying strings from file
我使用重载插入运算符将一些字符串存储在一个文本文件中
ostream & operator << (ostream & obj,Person & p)
{
stringstream ss;
ss << strlen(p.last) << p.last << strlen(p.first) << p.first
<< strlen(p.city) << p.city << strlen(p.state) << p.state;
obj << ss.str();return obj;
}
文件的内容看起来像这个
4bill5gates7seattle10washington
我现在需要先读取长度并显示字符串。并继续显示所有字符串。如何对过载的提取运算符执行此操作?
每次读取一个字符,并使用std::string::push_back
附加到字符串变量。有一个std::stoi
,它将把你的字符串长度转换成一个整数。我建议您在创建文本文件时,在整数长度后加一个空格,然后您可以只使用cin >> string_length
,避免使用if
语句来控制何时找到数字的末尾或新字符串的开头。
此外,如果你向我们展示你所做的尝试,那将是更有益的,这样我们就可以更具体地帮助你。
您可以执行以下操作:
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::istringstream in("4bill5gates7seattle10washington");
std::vector<std::string> strings;
unsigned length;
while(in >> length) {
std::string s;
if(in >> std::setw(length) >> s)
strings.push_back(s);
}
for(const auto& s : strings)
std::cout << s << 'n';
}
免责声明:文件格式不正确。
注意:这不是提取"个人",而是提取字段。我把这个留给你。
使operator <<
像这个
ostream & operator >> ( ostream & obj, Person & p )
{
obj << strlen( p.last ) << " " << p.last << " " << strlen( p.first ) << " " << p.first << " "
<< strlen( p.city ) << " " << p.city << " " << strlen( p.state ) << " " << p.state;
return obj;
}
和operator >>
类似于这个
istream & operator >> ( istream & obj, Person & p )
{
obj >> p.last >> p.first >> p.city >> p.state;
return obj;
}
相关文章:
- 显示字符串的集合和子集
- 为什么我的 cout 在输出中没有显示字符串?
- 如何让我的构造函数和函数工作,以便我的 main() 能够同时显示字符串和 int 数据
- 为什么程序显示字符串超出范围
- C++ 显示字符串变量"<不完整类型>的调试窗口
- 以C++显示字符串矢量<int>地图
- 用于显示字符串每个字符的 for 循环 |C++
- 错误-无法访问Omnet中创建新节点的显示字符串
- 为什么 cout 不显示字符串变量 rnd
- c++中的sizeof显示字符串大小少一个
- 从文件中读取和显示字符串
- 在VC2010中使用Char数组显示字符串时发生运行时错误
- 尝试对角线显示字符串时,我遇到c ++程序崩溃
- 无法使用用户定义的字符串类显示字符串
- 如何显示字符串中多次出现的字符
- 显示字符串的C++
- C++字符串。为什么答案显示字符串"狗"大于"猫",然后"猫"大于"狗"?
- 错误在哪里?显示字符串C++Vignere密码
- 在C++中显示字符串的矢量
- 显示字符串的地址