How to read .txt file line from index 0

0

I have the following code snippet that reads line by line from a text file, end to beginning of string . How do I change it, so that this action occurs in reverse?

while (getline (entrada, linha)){
    int tam_linha = linha.size(); /* Tamaho da linha, caracateres por linha */

    for(int i=tam_linha-1; i>=0; i--)
    {
        if(linha[i] == ' ' && linha[i-1] == linha[i])
        {
            linha.erase(linha.begin()+i);                    
        }
    }
}
    
asked by anonymous 25.06.2017 / 22:10

3 answers

2

If the intention is to read line by line of a text file by filtering the contents of each line with the removal of double spaces by single spaces, follow 2 C ++ solutions using STL :

Using the functions std::unique() and std::string::erase() :

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

bool check_double_spaces( char a, char b) { return ((a == b) && (a == ' ')); }

int main()
{
    string linha;
    ifstream entrada("arquivo.txt");

    while( getline( entrada, linha) )
    {
        string::iterator end = unique( linha.begin(), linha.end(), check_double_spaces );

        linha.erase( end, linha.end() );

        cout << linha << endl;
    }

    return 0;
}

Using the functions std::string::find() and std::string::replace() :

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string linha;
    ifstream entrada("arquivo.txt");
    size_t idx;

    while( getline( entrada, linha ) )
    {
        while( (idx = linha.find("  ")) != string::npos ) // Dois espaços
            linha.replace( idx, 2, " " ); // Um espaço

        cout << linha << endl;
    }

    return 0;
}
    
26.06.2017 / 16:05
1
int main(void) {
    FILE *ficheiro = fopen("arquivo.txt", "r");
    if(ficheiro == NULL){
        printf("\nErro");
        exit(1);
    }
    char linha[100];
    while(fgets(linha, 100, ficheiro){ //essa função vai ler todo o ficheiro
        printf("\n%s", linha);
    }
}
    
25.06.2017 / 23:13
1

Another solution (if I understood correctly) would be to use regular expressions:

#include <string>
#include <iostream>
#include <regex>
using namespace std;


int main()
{
    regex reg("[ ]+");
    string linha;

    while (getline(cin, linha))
        cout << regex_replace(linha, reg, " ") << "\n\n";

    return 0;
}

All multiple spaces will be replaced by only one.

    
26.06.2017 / 21:44