искать и сообщать о несовместимости - PullRequest
0 голосов
/ 06 марта 2012

Я пишу консольное приложение C ++.После создания Matrix с размерами (int) rowSize и columnSize я хотел записать буквы в текстовом файле в матрицу, но цикл так и не запускается, потому что расположение читателя равно -1, и я не смог взять его в 0. Есть идеи?

void writeText2Vec(ifstream & reader, tmatrix<char> & table){
    string s;
    int length, row = 0, column = 0; //beginning: column and
                                     //row ids are set to 0.
    reader.seekg(0); //reset the pointer to start

    cout << reader.tellg(); // it results in -1.
    while (getline(reader,s)){
        //for each line while loop occurs.
        length = s.length();
        for(column = 0; column < length; column++)
        {
            table[row][column] = s.at(column);
            //writing the letter to matrix.
        }
        row++;
    }

bool openFile(ifstream & reader, string filename){
    reader.open(filename.c_str());

    if (reader.fail()){
        exit("File cannot be found.");
        return false;
    }
    else {
        return true;
    }
}

bool check(ifstream & reader, int & rowSize, int & columnSize){
    //checks for valid characters, if they are
    //alphabetical or not and for the length.

    string s;
    int len = 0, max = 0;
    while (getline(reader,s)){
        //runs for every line.
        rowSize++; //calculation of row size

        while (len < s.length()){
            if (!(isalpha(s.at(len)))){
                // Check to see if all characters are alphabetic.
                exit("Matrix contains invalid characters!");
                return false;
            }
            len++;
        }
        if (max == 0){
            //if max is not set.
            max = len;
            len = 0;
        }
        else if (!(max == len)){
            //if they are different, then appropriate
            //error message is returned.
            exit("Matrix is not in a correct format!");
            return false;
        }
        else {
            //else it resets.
            len = 0;
        }
    }
    rowSize -= 1;
    columnSize = s.length(); //the last length is equal to column size
    return true;
}

1 Ответ

2 голосов
/ 06 марта 2012

tellg() возвращает -1, когда произошла ошибка.Возможно, поток находился в состоянии ошибки при вызове функции.Если вы прочитали до конца один раз, значит, произошел сбой ввода, и поток находится в состоянии ошибки, которое необходимо очистить перед выполнением любых других операций: reader.clear().

...