繁体   English   中英

从文件读取和显示字符串

[英]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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM