从文件中读取和显示字符串

reading and displaying strings from file

本文关键字:显示 字符串 读取 文件      更新时间:2023-10-16

我使用重载插入运算符将一些字符串存储在一个文本文件中

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;
}