Ir para conteúdo
Fórum Script Brasil
  • 0

Mudar para c++ e forms + builder


D0cz

Pergunta

Olá, vou tentar me apresentar um pouco e assim vocês podem me conhecer melhor. Sou estudante da terceira fase de CdC e ultimamente venho me perguntando se fiz a escolha certa, já que até então tudo parece complicado de fazer sozinho (programação) e parece que não tenho a motivação necessária :/

Eu gosto de tecnologia, redes, matemática e programação no início eu mandava muito bem mas do nada perdi totalmente a vontade de ir atrás e programar soznho dependendo apenas de grupos...

Alguns dias atrás a professora de C++ fez um request de um projeto em dupla e assunto livre, ou seja, qualquer coisa desde que fosse em C++ e tivesse forms como ela diria ^_^ Então eu e um colega ficamos pensando e pensando e surgiu a idéia de realizar um Editor de Textos, ele fez tudo baseado em um tutorial e mudou a parte visual, muito bem até então, problema que eu não fiz nada por falha minha e acabei deixando de aprender algo interessante e me firmar nessa área de uma vez por todas.

A questão aqui é que eu quero fazer um projeto só meu e que tenha um fundamento legal, e foi ai que lembrei de um programa para linux que meu grande primo Karl fez, problema que só roda por terminal no linux(e obviamente não possui interface), e eu preciso que tenha uma janela com botões e que rode no windows...

Gostaria de esclarecer uma pequena coisa, não quero que vocês me entreguem qqlqr coisa pronta, apenas me ajudem de forma didática os caminhos para eu ter sucesso nesse trabalho e poder estufar o peito e dizer que eu fui atrás, pesquisei e com muita ajuda dos camaradas eu realizei uma coisa: um programa interessante e com a minha cara.

Para quem gostaria de ver o programa rodando, basta acessar http://sourceforge.net/projects/fpeek/ e baixar no seu linux para ver o funcionamento (livre de vírus, não esquenta o/ )

E para aqueles programadores fod*es aqui vai o código:

/*
    Copyright (C) <2009>  <Karl Phillip Buhr>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "fpeek.h"

#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <algorithm>

bool _display_line_num = false;

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        std::cerr << "Usage: " << argv[0] << " <options> <file>\n" <<
                     "Try '" << argv[0]<< " --help' for more information." << std::endl;
        return -1;
    }

    // Parse command line options
    std::vector<std::string> args;
    args = cmd_line_handle(argc, argv);

    // Checking is file exists
    char* filename = argv[argc-1];
    std::ifstream file(filename);
    if (!file.is_open())
    {
        std::cerr << filename << ": No such file" << std::endl;
        exit(0);
    }

    // We do not print lines of binary files
    char c = 0;
    while (file)
    {
        file.get(c);
        if (c < -96)
        {
           std::cerr << filename << ": Cannot open binary file" << std::endl;
           exit(0);
        }
    }
    file.close();

    display_lines(filename, args);

    return 0;
}

void cmd_line_help(char* invocation)
{
    std::cerr << "Usage: "<< invocation <<" [options] <file>\n\n" <<
                 "Options:\n" <<
                 "    -d,                   Print line numbers before the result.\n" <<
                 "    -l,  --line N         Print line N from file. Multiple lines must be separated by the symbol ','.\n" <<
                 "    -r,  --range N-M      Print range of lines from N to M. Must be separated by '-'.\n" <<
                 "                          You can also use ',' when working with multiple ranges.\n" <<
                 "    -h                    Display this message\n" <<
                 "\n" <<
                 "You can visit fpeek homepage at: https://sourceforge.net/projects/fpeek/\n" << std::endl;

    exit(0);

    return;
}

std::vector<std::string> cmd_line_handle(int argc, char **argv)
{
    std::vector<std::string> args;

    for(int i=1; i<argc; i++)
    {
        if (argv[i][0] != '-') continue;

        if (!strcmp(argv[i], "--help") ||
            !strcmp(argv[i], "-help" ) ||
            !strcmp(argv[i], "-h"    ))
        {
            cmd_line_help(argv[0]);
            return args;
        }
        else if(!strcmp(argv[i], "-d"))
        {
            _display_line_num = true;
        }
        else if( (!strcmp(argv[i], "-l") || !strcmp(argv[i], "--line") ) && i+1 < argc)
        {
            args.push_back(argv[i+1]);
            i++;
        }
        else if( (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--range") ) && i+1 < argc)
        {
            args.push_back(argv[i+1]);
            i++;
        }
        else
        {
            std::cerr << "Invalid parameter: " << argv[i] << ".\n" << std::endl;
            cmd_line_help(argv[0]);
            return args;
        }
    }

    if (args.size() == 0)
        cmd_line_help(argv[0]);

    return args;
}

void display_lines(char* filename, std::vector<std::string> args)
{
    std::vector<int> line_vec;

    if (args.size() > 0)
    {
        for (size_t i = 0; i < args.size(); i++)
        {
            // Parse single lines
            char* token = strtok(const_cast<char *>(args.at(i).c_str()), "," );
            while (token != NULL)
            {
                line_vec.push_back(atoi(token));
                token = strtok(NULL, ",");
            }

        }

        for (size_t i = 0; i < args.size(); i++)
        {
            // Parse range of lines
            int range_beg = 0;
            int range_end = 0;
            char* token = strtok(const_cast<char *>(args.at(i).c_str()), "-" );
            while (token != NULL)
            {
                if (!range_beg)
                    range_beg = atoi(token);
                else
                    range_end = atoi(token);

                token = strtok(NULL, ",");
            }

            for (int i = range_beg; i <= range_end; i++)
                line_vec.push_back(i);
        }
    }


    // Magic: search through file and display lines
    std::ifstream file(filename);

    std::string line;
    int pos = 1;
    while (std::getline(file, line))
    {
        // Find if current line should be displayed
        std::vector<int>::iterator iter = std::find(line_vec.begin(), line_vec.end(), pos);
        if (*iter == pos)
        {
            if (_display_line_num)  // If -d was requested, should print the line number too
            {
                std::cout << pos << ": ";
            }

            std::cout << line << std::endl;
        }

        pos++;
    }

    return;
}
e aqui a header:
/*
    Copyright (C) <2009>  <Karl Phillip Buhr>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include <string>

void cmd_line_help(char* invocation);
std::vector<std::string> cmd_line_handle(int argc, char **argv);
void display_lines(char* filename, std::vector<std::string> args);

Ficarei MUITO grato por qualquer ajuda, estou um tanto perdido e preciso definir logo se consigo ser um bom programador/seguir as dicas corretamente. E claro que entenderei se não foi muito possível "converter" esse programa

Bruno.

Link para o comentário
Compartilhar em outros sites

1 resposta a esta questão

Posts Recomendados

  • 0

Tirando o main, essa parte é totalmente portável:


std::vector<std::string> cmd_line_handle(int argc, char **argv)
{
std::vector<std::string> args;

for(int i=1; i<argc; i++)
{
if (argv[i][0] != '-') continue;

if (!strcmp(argv[i], "--help") ||
!strcmp(argv[i], "-help" ) ||
!strcmp(argv[i], "-h" ))
{
cmd_line_help(argv[0]);
return args;
}
else if(!strcmp(argv[i], "-d"))
{
_display_line_num = true;
}
else if( (!strcmp(argv[i], "-l") || !strcmp(argv[i], "--line") ) && i+1 < argc)
{
args.push_back(argv[i+1]);
i++;
}
else if( (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--range") ) && i+1 < argc)
{
args.push_back(argv[i+1]);
i++;
}
else
{
std::cerr << "Invalid parameter: " << argv[i] << ".\n" << std::endl;
cmd_line_help(argv[0]);
return args;
}
}

if (args.size() == 0)
cmd_line_help(argv[0]);

return args;
}

void display_lines(char* filename, std::vector<std::string> args)
{
std::vector<int> line_vec;

if (args.size() > 0)
{
for (size_t i = 0; i < args.size(); i++)
{
// Parse single lines
char* token = strtok(const_cast<char *>(args.at(i).c_str()), "," );
while (token != NULL)
{
line_vec.push_back(atoi(token));
token = strtok(NULL, ",");
}

}

for (size_t i = 0; i < args.size(); i++)
{
// Parse range of lines
int range_beg = 0;
int range_end = 0;
char* token = strtok(const_cast<char *>(args.at(i).c_str()), "-" );
while (token != NULL)
{
if (!range_beg)
range_beg = atoi(token);
else
range_end = atoi(token);

token = strtok(NULL, ",");
}

for (int i = range_beg; i <= range_end; i++)
line_vec.push_back(i);
}
}


// Magic: search through file and display lines
std::ifstream file(filename);

std::string line;
int pos = 1;
while (std::getline(file, line))
{
// Find if current line should be displayed
std::vector<int>::iterator iter = std::find(line_vec.begin(), line_vec.end(), pos);
if (*iter == pos)
{
if (_display_line_num) // If -d was requested, should print the line number too
{
std::cout << pos << ": ";
}

std::cout << line << std::endl;
}

pos++;
}

return;
}
[/codebox]

O que você precisa fazer:

1. Trocar a função display_lines para retornar um std::string, você pode substituir o std::cout por uma variável do tipo std::ostringstream e retornar variável.str().

2. Mandar os argumentos pra função display_lines (como se fosse um aplicativo de terminal normal, note que você ou tem que interpretar os argumentos pro formato que a função espera (a cmd_line_handle faz isso), ou enviar no formato pronto já)

3. Pegar o resultado;

4. Interpretar o resultado;

5. Mostrar na interface gráfica.

Abraços.

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...