File import. txt C++

Asked

Viewed 61 times

-1

When I import a space is added at the beginning of the text. example: "A" How do I ignore him ?

Texto::Texto() {
    string pal, arquivoNome;
    char *palavra_aux;
    int i = 0;
    char *token = NULL;

    cout<<"Digite o nome do arquivo que contém o texto a ser corrigo, com a extensão: ";
    getline(cin,arquivoNome);

    ifstream arquivo(arquivoNome);
    pal.assign((istreambuf_iterator<char>(arquivo)),(istreambuf_iterator<char>())); // Tranfosma o conteudo do do arquivo para char

    palavra_aux = new char[pal.length()+1];
    strcpy(palavra_aux, pal.c_str());

    texto = palavra_aux;

    if (arquivo.is_open()) {

        token = strtok(palavra_aux," ,.;-? ");

        while (token != NULL) {
            palavra[i] = new Palavra(token);
            i++;
            token = strtok (NULL, " ,.;-? ");
        }
    }
    else {
        cout << "Falha ao abrir o arquivo!" << endl;
    }

    arquivo.close(); // Fecha arquivo
    tam = i;
}
  • where the space appears? in the file or in a string?

  • in the string array, a space q does not even have in the file

1 answer

1


Your problem is in those lines

palavra_aux = new char[pal.length()+1];
strcpy(palavra_aux, pal.c_str());

You create the char vector with the string size + 1 and then use the strcpy that instantiates the size of the string to occupy the last positions of the vector, that is, fill the pal length.() vector positions and the one left over (in your case the first) will look like garbage, which in your case is showing a blank space.

palavra_aux = new char[pal.length()];

length already returns the string size not the last position.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.