【问题标题】:Bad reading from file (0 or "" values readed)从文件中读取错误(读取 0 或 "" 值)
【发布时间】:2012-10-12 17:38:57
【问题描述】:

这是我的类的定义:

class BPP
{
    unsigned            n;                  /* nº de instancias */
    vector<string>      nombre_instancia;   /* nombre de la instancia*/
    vector<unsigned>    n_objetos;          /* nº de objetos a almacenar en cada instancia */
    vector<unsigned>    C;          /* capacidad máxima de cada contenedor */
    vector<unsigned>    mejor;              /* mejor nº mínimo de contenedores usados (m*) */
    vector< vector<unsigned> > tam_objeto;

这是我完整的构造函数:

BPP :: BPP(char fich1[])
{
    ifstream file1; string str; unsigned a, b, c, d;
    file1.open(fich1);
    if (file1.is_open()){ 
        file1 >> (unsigned &) n;
        for (unsigned k = 0 ; k < n ; ++k){
            getline(file1, str); nombre_instancia.push_back(str);
            file1 >> a; n_objetos.push_back(a);
            file1 >> b; C.push_back(b);
            file1 >> c; mejor.push_back(c);
            for (unsigned h = 0 ; h < a ; ++h){
                file1 >> d; tam_objeto[k].push_back(d);
            }
        }
    }
    file1.close();
}

fich1 的前 5 行是:

10
 P_0 /*Notice the space in the beginning of the line, and in the end*/
150 120 52
30
34

输出是所有读取的值都是0(如果是无符号)或“”(如果是字符串)

【问题讨论】:

    标签: c++ string file constructor stream


    【解决方案1】:

    问题是10之后的换行符被:

    file1 >> (unsigned &) n; // Why the cast here?
    

    这意味着getline(file1, str) 调用仅读取换行符,即空行。接下来的输入操作是:

    file1 >> a;
    

    因为P_0 不是有效的unsigned int 而失败。此故障会阻止从file1 流(其failbit 已设置)的任何进一步读取。 要解决此问题,您只需调用两次getline(),忽略第一次调用的结果。

    检查所有读取的结果以检测失败。这样做会提醒您读取失败。

    【讨论】:

    • 我没有你说的,但还是不行。两次调用 getline() 会导致分段错误,甚至忽略它的结果(不要存储在变量中)
    • @freinn,你将一个变量传递给getline(),但之后忽略它的值。
    • 我已经做到了:getline(file1, str); getline(file1, str); nombre_instancia.push_back(str);
    • @freinn,我只是仔细检查过,这是解决一个问题的方法。检查读取结果以定位何时发生故障:if (file1 &gt;&gt; a) { // ok } else { // not ok }
    • 有没有办法忽略第一个空格并一步读取该行?现在可以了,我已经完成了getline(file1, str, '\n'); getline(file1, str, '\n');
    猜你喜欢
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多