简体   繁体   中英

reading and displaying strings from file

I stored some strings in a text file using overloaded insertion operator.

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

The contents of file look like this

4bill5gates7seattle10washington

I now need to read the length first and display the string.And continue to display all the strings.How to do this with an overloaded extraction operator?

Read it one character at a time and use std::string::push_back to append to a string variable. There's a std::stoi which will convert your string lengths to an integer. Might I suggest that when you create your text file that you put a whitespace after your integer length, then you can just cin >> string_length and avoid using if statements to control when you've found the end of a number, or the beginning of a new string.

Also, it would be more beneficial, if you showed us what you've attempted, so that we could help you more specifically.

You may do:

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

Disclaimer: The file format is evil.

Note: This does not extract a 'Person', but fields. I leave that to you.

Make operator << like this

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

and operator >> like this

istream & operator >> ( istream & obj, Person & p )
{
    obj >> p.last >> p.first >> p.city >> p.state;

    return obj;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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