C++primer:string流

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++primer:string流)