2011-10-20 71 views
0

尽管我对C++相当陌生,但我还没有完全熟悉这个术语,所以我对提前模糊的声音表示歉意!重载操作员帮助?

我的问题是我很努力地看到为什么我的while循环似乎停止我的重载操作函数中的其他方法;

#include "sample.h" 

#include <iostream> 
#include <vector> 
#include <cstdlib> 

using namespace std; 

sample::sample(vector<double> doubles){} 

sample::sample() {} 

ostream& operator<< (ostream &out, sample &sample) 
{ 
    out << "<" << sample.n << ":"; 
    return out; 
} 

istream& operator>> (istream &in, sample &sample) 
{ 
    char firstChar; 
    in >> firstChar; 

    if(firstChar != '<'){ 
     cout << "You've not entered the data in a valid format,please try again!1 \n"; 
     exit(1); 
    } 

    int n; 
    in >> n; 
    sample.n = n; 

    char nextChar; 
    in >> nextChar; 
    if(nextChar != ':'){ 
     cout << "You've not entered the data in a valid format,please try again!2 \n"; 
     exit(1); 
    } 

    vector<double> doubles; 
    double number; 
    while (in >> number){ 
     doubles.push_back(number); 
     cout << in << " " << number; 
    } 
    in >> lastChar; 

    return in; 
} 

int main(void) 
{ 
    sample s; 
    while (cin >> s){ 
     cout << s << "\n"; 
    } 

    if (cin.bad()) 
     cerr << "\nBad input\n\n"; 

    return 0; 
} 

我的输入是类似的东西;

< 6:10.3 50 69.9>

我试图让之后的所有双打“:”为载体,如果他们整数我可以做,但一旦“”进入它似乎停止。

如果我只是把整数,它似乎也停止while(in >> number)已经完成查找所有的数字后,这很好,但在我的主要功能cout<<命令似乎并不工作!

我哪里出错了?

回答

1

您必须遵守的标准流成语:每一个流隐式转换为一个布尔值(或空指针),以允许像检查if (in >> n)查看操作是否成功。所以首先你必须确保你的操作符符合这个要求(通过确保提取成功的流是“好的”)。其次,当你编写一个像while (in >> x) { /*...*/ }这样的循环时,循环终止后,你已经知道你的流不再好。因此,在返回之前,您必须先致电clear()

也许是这样的:

std::istream& operator>> (std::istream &in, sample &sample) 
{ 
    char c; 
    int n; 
    double d; 
    std::vector<double> vd; 

    if (!(in >> c)) { return in; }        // input error 
    if (c != '>') { in.setstate(std::ios::bad); return in; } // format error 

    if (!(in >> n)) { return in; }        // input error 

    if (!(in >> c)) { return in; }        // input error 
    if (c != ':') { in.setstate(std::ios::bad); return in; } // format error 

    while (in >> d) 
    { 
    vd.push_back(d); 
    } 

    in.clear(); 

    if (!(in >> c)) { return in; }        // input error 
    if (c != '>') { in.setstate(std::ios::bad); return in; } // format error 

    state.n = n; 
    state.data.swap(vd); 

    return in; 
} 

注意,如果整个输入操作成功,我们只修改sample对象。

+0

感谢Kerrek,我有一个更好的理解,但混淆清楚的方法实际上做什么?!当你调用一个清除函数时,我试图从数据的数字部分到最后一个字符? – r0bb077

+0

它根本不“走”; 'clear'只是重置错误标志,以便完全执行下一个提取操作(不会在错误的流上执行提取操作)。 –

+0

真棒,应该真的假设!再次感谢您的帮助! – r0bb077

0
cout << in << " " << number; 

你可能是指

cout << " " << number; 

什么

+0

对不起,作为一个绝望的代码来看看它输入向量中的数字时,我应该从代码中删除,当我把它粘贴在这里! – r0bb077