Removing specific index with user inputC# - if-statement

I'm trying to make input from users specify what index should be removed from a list.
They get a list with ID on the objects then type in the ID for the object they wan't to remove. The written ID begins at 1 but is actually 0; so when users type 1 it will be changed to 0.
I've also made it so they can't choose an input outside the range of the index. I had it working for while but then i wanted to unallow whitespace input from users and that's where i did something wrong with my code.
I've reverted it to the point before i started editing it but i can't seem to find what's wrong!
public static void menuLISTA()
{
menuTEXT.WriteFullLine("-Din Digitalgarderobs innehåll-");
Console.WriteLine("===============================================================");
if (newklädDataList.Count == 0)
{
Console.WriteLine();
Console.WriteLine("Din digitalgarderob är tom!");
Console.WriteLine();
Console.WriteLine("===============================================================");
Console.WriteLine("Tryck [Enter] för att fortsätta."); Console.ReadKey();
}
else if (newklädDataList.Count != 0)
{
for (int i = 0; i < newklädDataList.Count; i++)
{
klädDATALIST plagg = newklädDataList[i];
Console.WriteLine("ID: {4}\tMärke: {0}\tTyp: {1}\tFärg: {2}\tStorlek: {3}", plagg.märke, plagg.typ, plagg.färg, plagg.storlek, i + 1);
}
Console.WriteLine("===============================================================");
Console.WriteLine("Vill du ta bort ett klädesplagg? - Ange siffra -");
string input = Console.ReadLine();
int svar = int.Parse(input);
int svarID = svar - 1;
if (svar != 0 && svar < newklädDataList.Count)
{
newklädDataList.RemoveAt(svarID);
}
else if (svar == 0)
{
Console.WriteLine("\nVänligen ange ett giltigt plagg-ID. Tryck [Enter] för att fortsätta.");
Console.ReadKey();
Console.Clear();
menuLISTA();
}
else
{
Console.WriteLine("\nVänligen ange ett giltigt plagg-ID. Tryck [Enter] för att fortsätta.");
Console.ReadKey();
Console.Clear();
menuLISTA();
}
}
Console.Clear();
menuTITEL.menuKläd();
}

I solved it!
else if (newklädDataList.Count != 0)
{
for (int i = 0; i < newklädDataList.Count; i++)
{
klädDATALIST plagg = newklädDataList[i];
Console.WriteLine("ID: {4}\tMärke: {0}\tTyp: {1}\tFärg: {2}\tStorlek: {3}", plagg.märke, plagg.typ, plagg.färg, plagg.storlek, i + 1);
}
Console.WriteLine("===============================================================");
Console.WriteLine("Vill du ta bort ett klädesplagg? - Ange siffra -");
string input = Console.ReadLine();
int svar = int.Parse(input);
int svarID = svar - 1;
if (svarID == 0 || svar < newklädDataList.Count+1)
{
newklädDataList.RemoveAt(svarID);
Console.ReadKey();
Console.Clear();
menuLISTA();
}
else if (svar == 0)
{
Console.WriteLine("\nVänligen ange ett giltigt plagg-ID. Tryck [Enter] för att fortsätta.");
Console.ReadKey();
Console.Clear();
menuLISTA();
}
else
{
Console.WriteLine("\nVänligen ange ett giltigt plagg-ID. Tryck [Enter] för att fortsätta.");
Console.ReadKey();
Console.Clear();
menuLISTA();
}
}
Console.Clear();
menuTITEL.menuKläd();

Related

Program execution not stopping at scanf() after first read

I want that at every iteration of the do-while() loop the program stops at the scanf() function, but the program loops the same amount of times as the number of white spaces that the read string contains before stoping again at the scanf()
enum Comando
{
AYUDA,
LOGIN,
LOGOUT,
LISTAR_BUSES,
LISTAR_RUTAS,
LISTAR_VIAJES,
NULL_COMMAND
};
//Funcion que registra el comando ingresado por el usuario para indicarle al programa que es lo que debe hacer
pair<Comando, queue<char*>> ProcesarComando(char comandoEntero[20]);
void MostrarAyuda();
int main()
{
bool salir = false;
char comando[20];
Comando cmd;
do
{
printf("\n\t$ ");
scanf(" %s", comando);
cmd = ProcesarComando(comando).first;
switch(cmd)
{
case AYUDA:
break;
case LOGIN:
break;
case LOGOUT:
break;
case LISTAR_BUSES:
break;
case LISTAR_RUTAS:
break;
case LISTAR_VIAJES:
break;
case NULL_COMMAND:
break;
}
}
while(!salir);
//system("pause");
return 0;
}
pair<Comando, queue<char*>> ProcesarComando(char comandoEntero[20])
{
int pos = 0;
char *argumento, *comandoNombre;
bool tieneParametros = false;
pair<Comando, queue<char*>> retorno;
argumento = new char[20];
while(comandoEntero[pos] != '\0')
{
if(comandoEntero[pos] == '<'|| comandoEntero[pos] == '[')
{
tieneParametros = true;
}
else if(tieneParametros && comandoEntero[pos] != ' ' && comandoEntero[pos] != '<' && comandoEntero[pos] != '>' && comandoEntero[pos] != '[' && comandoEntero[pos] != ']')
{
strncat(argumento, &comandoEntero[pos], 1);
}
else if(tieneParametros && comandoEntero[pos] == ' ')
{
cout<<"HOLAAAAAAA";
retorno.second.push(argumento);
memset(argumento, '\0', strlen(argumento));
tieneParametros = false;
}
pos++;
}
comandoNombre = new char[20];
comandoNombre = strtok(comandoEntero, " ");
if(strcmp(comandoNombre, "ayuda") == 0)
{
retorno.first = AYUDA;
return retorno;
}
else if(strcmp(comandoNombre, "login") == 0)
{
retorno.first = LOGIN;
return retorno;
}
else if(strcmp(comandoNombre, "logout") == 0)
{
retorno.first = LOGOUT;
return retorno;
}
else if(strcmp(comandoNombre, "listar_buses") == 0)
{
retorno.first = LISTAR_BUSES;
return retorno;
}
else if(strcmp(comandoNombre, "listar_rutas") == 0)
{
retorno.first = LISTAR_RUTAS;
return retorno;
}
else if(strcmp(comandoNombre, "listar_viajes") == 0)
{
retorno.first = LISTAR_VIAJES;
return retorno;
}
// printf("\n%s", retorno.second.front());
// retorno.second.pop();
// printf("\n%s", retorno.second.front());
retorno.first = NULL_COMMAND;
return retorno;
}
So, because the program is not stoping at the scanf(), it is printing all those money signs but without letting me interact with the program until the amount of the string white spaces are reached...
I know that it may be something dumb, but couldn't figure it out, hope that you guys could help me.THANKS :v
Here I am posting a proper C++ implementation of your code. I know that code-only answers are not recommended. But here, I don't have much to tell you. You need to yourself check about the things you lack knowledge about. Better search things on this site.
#include <algorithm>
#include <iostream>
#include <queue>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
enum Comando {
AYUDA,
LOGIN,
LOGOUT,
LISTAR_BUSES,
LISTAR_RUTAS,
LISTAR_VIAJES,
NULL_COMMAND
};
auto ProcesarComando(std::string comandoEntero) {
std::string argumento, comandoNombre;
bool tieneParametros = false;
std::queue<std::string> retorno;
for (auto &&i : comandoEntero)
if (i == '<' or i == '[')
tieneParametros = true;
else if (tieneParametros and std::string(" []<>").find(i) == size_t(-1))
argumento.push_back(i);
else if (tieneParametros and i == ' ') {
std::cout << "HOLAAAAAAA\n";
retorno.push(argumento);
argumento.clear();
tieneParametros = false;
}
std::stringstream(comandoEntero) >> comandoNombre;
const std::vector<std::string> cmd = {"ayuda", "login",
"logout", "listar_buses",
"listar_rutas", "listar_viajes"};
return std::make_pair(
static_cast<Comando>(std::find(cmd.begin(), cmd.end(), comandoNombre) -
cmd.begin()),
retorno);
}
int main() {
do {
std::cout << "\n$ ";
std::string comando;
std::getline(std::cin, comando);
switch (ProcesarComando(comando).first) {
case AYUDA:
break;
case LOGIN:
break;
case LOGOUT:
break;
case LISTAR_BUSES:
break;
case LISTAR_RUTAS:
break;
case LISTAR_VIAJES:
break;
default: // case NULL_COMMAND:
}
} while (true);
}

Bug color with my console menu

I am trying to do a menu driven by the keyboard's arrows. For this, I change the background of the selected item, like this:
But once I go to the last item and go up again, this happens:
There is my code for the selected items:
void Print::Select(int pos, int realpos)
{
if (pos == realpos)
SetconsoleTextAttribute(handle, 112);
else
SetConsoleTextAttribute(handle, m_white);
}
The entire code:
#include <Windows.h>
#include <iostream>
#include <conio.h>
#include "Options.hpp"
#include <math.h>
#define left_arrow 75
#define right_arrow 77
#define down_arrow 80
#define up_arrow 72
#define page_up 73
#define page_down 81
Config g_options;
class Print
{
public:
void Infos();
void State(bool state);
void Select(int pos, int realpos);
void Loop();
void CheckInput();
int m_red = 0xC;
int m_green = 0xA;
int m_white = 0x7;
int m_selection_color = 70;
char m_input;
int m_min = 1;
int m_max = 0;
unsigned int m_selection_pos = 1;
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
}; extern Print g_print;
void Print::CheckInput()
{
m_input = _getch();
Sleep(30);
if (m_input == page_up && g_options.current_tab != g_options.tabs[3])
g_options.current_tab = g_options.tabs[rand() % 3];
else if (m_input == page_down && g_options.current_tab != g_options.tabs[0])
g_options.current_tab = g_options.tabs[rand() % 3];
if (m_input == up_arrow && m_selection_pos != m_min)
m_selection_pos -= 1;
else if (m_input == down_arrow && m_selection_pos != m_max)
m_selection_pos += 1;
else if (m_input == left_arrow || m_input == right_arrow)
{
if (g_options.current_tab == g_options.tabs[0])
{
switch (m_selection_pos)
{
case 1:
g_options.aim_enabled = !g_options.aim_enabled; break;
case 2:
g_options.aim_autoconfig = !g_options.aim_autoconfig; break;
case 3:
g_options.aim_rcs = !g_options.aim_rcs; break;
case 4:
if (m_input == right_arrow) { g_options.aim_smooth++; break; }
else if (m_input == left_arrow) { g_options.aim_smooth--; break; }
}
}
if (g_options.current_tab == g_options.tabs[1])
{
switch (m_selection_pos)
{
case 1:
g_options.esp_enabled = !g_options.esp_enabled; break;
case 2:
g_options.esp_ennemies = !g_options.esp_ennemies; break;
case 3:
g_options.esp_friends = !g_options.esp_friends; break;
}
}
if (g_options.current_tab == g_options.tabs[2])
{
switch (m_selection_pos)
{
case 1:
g_options.trigger_enabled = !g_options.trigger_enabled;
case 2:
g_options.triggerbot_ennemies = !g_options.esp_ennemies;
case 3:
g_options.trigger_team = g_options.trigger_team;
case 4:
if (m_input == left_arrow) { g_options.trigger_delay -= 1; break; }
else if (m_input == right_arrow) { g_options.trigger_delay += 1; break; }
}
}
if (g_options.current_tab == g_options.tabs[3])
g_options.noflash_enabled = !g_options.noflash_enabled;
}
}
void Print::Select(int pos, int realpos)
{
if (pos == realpos)
{
SetConsoleTextAttribute(handle, 112);
}
else if (pos != realpos)
SetConsoleTextAttribute(handle, m_white);
}
void Print::State(bool state)
{
if (state)
{
SetConsoleTextAttribute(handle, m_green);
printf("[ON]\n");
SetConsoleTextAttribute(handle, m_white);
}
else if (!state)
{
SetConsoleTextAttribute(handle, m_red);
printf("[OFF]\n");
SetConsoleTextAttribute(handle, m_white);
}
}
void Print::Infos()
{
system("cls");
std::cout << "========= " << g_options.current_tab << " =========" << std::endl << std::endl;
if (g_options.current_tab == g_options.tabs[0])
{
Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.aim_enabled);
Select(2, m_selection_pos); std::cout << "Autoconfig: "; State(g_options.aim_autoconfig);
Select(3, m_selection_pos); std::cout << "Recoil control: "; State(g_options.aim_rcs);
Select(4, m_selection_pos); std::cout << "Smooth: " << g_options.aim_smooth;
}
else if (g_options.current_tab == g_options.tabs[1])
{
Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.esp_enabled);
Select(2, m_selection_pos); std::cout << "Glow ennemy: "; State(g_options.esp_ennemies);
Select(3, m_selection_pos); std::cout << "Glow team: "; State(g_options.esp_friends);
}
else if (g_options.current_tab == g_options.tabs[2])
{
Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.trigger_enabled);
Select(2, m_selection_pos); std::cout << "Shoot ennemy: "; State(g_options.triggerbot_ennemies);
Select(3, m_selection_pos); std::cout << "Shoot team: "; State(g_options.trigger_team);
Select(4, m_selection_pos); std::cout << "Delay: " << g_options.trigger_delay;
}
else if (g_options.current_tab == g_options.tabs[3])
{
Select(1, m_selection_pos); std::cout << "Noflash: "; State(g_options.noflash_enabled);
}
}
void Print::Loop()
{
while (true)
{
Infos();
if (g_options.current_tab == g_options.tabs[0] || g_options.current_tab == g_options.tabs[2])
m_max = 4;
else if (g_options.current_tab == g_options.tabs[1])
m_max = 3;
else if (g_options.current_tab == g_options.tabs[3])
m_max = 1;
CheckInput();
}
}
I just noticed that the bug occurs only with the smooth option

cant create new files after some created in a loop

re-formuling the question, I have this code that reads the names of 2500 files in a folder and then read them one by one and extract specific information from them to write that info in new files, the problem is that after extracting the info of exactly 533 files it doesnt open the next ones, the extrae function tells me by logs that the files cant be opened, but i make sure that every time a file has opened i close it after i extract this info i need, so i dont know why it doesnt allow me to read the files after the 533 files read,help plz
this is my function that extract the info
enter code here
std::vector<Cliente> Extraccion::extrae(std::string path, std::vector<Journal> conjunto, std::vector<BanderaEnvio> envios, std::vector<CFD> cfd, std::vector<TIM> tim, std::vector<CentroReparto> lista, std::vector<DomiciliacionS702> domis, std::vector<CargosEnAclaracion> cargos, std::vector<CaracImpresion> impresion)
{
std::vector<Cliente> clientesF;
std::vector<Encabezado> encabezados;
clientesF.clear();
encabezados.clear();
Cliente *nuevoCliente = new Cliente();
int i = 0;
std::string bin = "";
int r =0;
int countCli=0;
long tmaline;
bool bwrite = true;
std::string canal = "";
std::string msglog = "";
int ctesOmitidos = 0;
int openFile = 0;
std::string linea = "";
std::fstream file;
std::cout<<"---Extrae el Archivo "<<path<<std::endl;
file.open(path.c_str(), ios::in);
if (file.good())
{
// //std::cout<<"____________________entra a leer archivo______________________"<<std::endl<<std::endl;
while(!file.eof())
{
/*lee la longitud de la linea */
std::getline(file,linea);
i++;
// std::cout<<"LINEA "<<i<<std::endl;
tmaline = linea.length();
canal = linea.substr(0, 3);
/*Metemos la Cabecera(canales con HD al inicio), donde viene el num de cliente y su producto */
if(linea.substr(0, 2) == "HD")
{
Encabezado cab(linea.substr(3,6),util.trim(linea.substr(66,30)));//new Encabezado(linea.substr(3,6),util.trim(linea.substr(66,30))); //.util.trim()
encabezados.push_back(cab);
// //std::cout<<"AQUI ESTA EL PRODUCTO : "<<cab.getProducto()<<std::endl;
// //std::cout<<util.trim(linea.substr(66,30)); //cab.producto;
}
else
{
//cout<<"---------no hay encabezados---------"<<std::endl<<std::endl;
if (canal == "BH1")
{
//case 1/*"BH1"*/:
if(nuevoCliente->strCliente.numCta != "0")
{
if (bwrite == true)
{
if(nuevoCliente->strCliente.saldoEPP=="")
nuevoCliente->strCliente.saldoEPP="[0.00]";
if(nuevoCliente->strCliente.saldoPromCompr=="")
nuevoCliente->strCliente.saldoPromCompr="0.00";
if(nuevoCliente->strCliente.saldoPromDispo=="")
nuevoCliente->strCliente.saldoPromDispo="0.00";
if(nuevoCliente->strCliente.saldoProm=="")
nuevoCliente->strCliente.saldoProm="0.00";
if(nuevoCliente->strCliente.saldoPromDispMax=="")
nuevoCliente->strCliente.saldoPromDispMax="0.00";
clientesF.push_back(*nuevoCliente);
}
else
{
// //std::cout<<"Falso para: "<<nuevoCliente->strCliente.numCta<<"|"<<nuevoCliente->strCliente.numtargta<<std::endl;
countCli--;
ctesOmitidos++;
}
nuevoCliente = new Cliente();
nuevoCliente->strCliente.numCta = "0";
msglog = "";
bwrite = true;
//nuevoCliente = new Cliente();
}
if(tmaline >= 1308)
{
++countCli;
nuevoCliente->strCliente.numCta = linea.substr(9,19); //NUMERO DE CUENTA
nuevoCliente->strCliente.numCliente = linea.substr(47,19); //NUMERO DE CLIENTE
bin=linea.substr(12, 6);
nuevoCliente->strCliente.jobOrigen = getProdJob(getNombreENTR(path),encabezados[0].getProducto().substr(0, 8)); //.get(0).getProducto().substr(0,8));
nuevoCliente->strCliente.numCta = linea.substr(9,19); //NUMERO DE CUENTA
nuevoCliente->strCliente.numtargta = linea.substr(28,19);
nuevoCliente->strCliente.domiciliacion = getDomiciliacion(domis, nuevoCliente->strCliente.numtargta); //DOMICILIACION
nuevoCliente->strCliente.cargosEnAclaracion=getCargo(cargos, nuevoCliente->strCliente.numCta+nuevoCliente->strCliente.numtargta); //CARGOS ACLARACION
nuevoCliente->strCliente.numCliente = linea.substr(47,19); //NUMERO DE CLIENTE
nuevoCliente->strCliente.numContra = " "; //NUMERO DE CONTRATO
nuevoCliente->strCliente.bandEnvio = linea.substr(867,1); //BANDERA ENVIO
nuevoCliente->strCliente.codBar = getCodigoBarras(conjunto,linea.substr(28,19)); //NUMERO DE TARJETA regresa CODIGO BARRAS
nuevoCliente->strCliente.medEnvio = getBandEnvio(envios,linea.substr(867,1)); //BANDERA regresa MEDIO ENVIO
nuevoCliente->strCliente.numProd = linea.substr(3,6);
nuevoCliente->strCliente.nomProd = getProducto(encabezados,linea.substr(3,6)); //NUM PRODUCTO regresa NOMBRE PRODUCTO
nuevoCliente->strCliente.fechaAper = completaFechaAp(linea.substr(981,6)); //FECHA APERTURA
nuevoCliente->strCliente.saldoActCorte = convierteCifras(linea.substr(206,12)); //SALDO ACTUAL AL CORTE
nuevoCliente->strCliente.saldoTotalCorte = convierteCifras(linea.substr(1296,12));//SALDO TOTAL AL CORTE
nuevoCliente->strCliente.mesesVencidos = linea.substr(739,1); //MESES VENCIDOS
nuevoCliente->strCliente.fechaLimite = completaFechaAp(linea.substr(230,6)); //FECHA LIMITE
nuevoCliente->strCliente.fechaCorte = completaFechaAp(linea.substr(224,6)); //FECHA CORTE
nuevoCliente->strCliente.fechaCorteArch = encabezados[0].getProducto().substr(0,4)+encabezados[0].getProducto().substr(6,2);//"FECHA";//getFechaArch(path); //FECHA CORTE ARCHIVO
nuevoCliente->strCliente.nombre = util.trim(linea.substr(486,40));//.util.trim(); //NOMBRE
nuevoCliente->strCliente.cp = util.trim(linea.substr(726,12));//.util.trim(); //CODIGO POSTAL
nuevoCliente->strCliente.cr = getCentroReparto(lista, nuevoCliente->strCliente.cp);
nuevoCliente->strCliente.dir1 = util.trim(linea.substr(526,40));//.util.trim(); //{
nuevoCliente->strCliente.dir2 = util.trim(linea.substr(566,40));//.util.trim();
nuevoCliente->strCliente.dir3 = util.trim(linea.substr(606,40));//.util.trim(); //DIRECCION
nuevoCliente->strCliente.dir4 = util.trim(linea.substr(646,40));//.util.trim();
nuevoCliente->strCliente.dir5 = util.trim(linea.substr(686,40));//.util.trim(); //}
nuevoCliente->strCliente.altBlockCode = linea.substr(869,1); //ALT BLOCK CODE
nuevoCliente->strCliente.blockCode = linea.substr(868,1); //BLOCK CODE
nuevoCliente->strCliente.uuID =getUId(cfd, tim,nuevoCliente->strCliente.numCta.substr(3,16)); //UUID
nuevoCliente->strCliente.tipo = isNuevo(nuevoCliente->strCliente.fechaAper, nuevoCliente->strCliente.fechaCorte, 30);
}
else
{
if (tmaline >= 66)
{
nuevoCliente->strCliente.numCliente = linea.substr(47,19);
nuevoCliente->strCliente.numCta = linea.substr(9,19);
}else
{
nuevoCliente->strCliente.numCliente = "No Identificado";
nuevoCliente->strCliente.numCta = "XX";
}
bwrite = false;
msglog = msglog + "Canal BH1 Linea " + std::to_string(i)+"; ";
}
} /*Fin if Canal BH1*/
else if (canal == "BH2")
{
/*Lectura Canal BH2*/
if (tmaline >= 781)
{
std::string plan = linea.substr(79,5); //PLAN
int p = atoi(plan.c_str());//integer.parseInt(plan);
if(p>=90000 && p<=91200)
{ // [90000,91200]
std::string saldo = convierteCifras(linea.substr(769,12));
nuevoCliente->strCliente.saldoEPP+="["+saldo+"]";
//cout<<" BH2 saldoEPP: "<<nuevoCliente->strCliente.saldoEPP <<" Cliente :"<<nuevoCliente->strCliente.numCliente<<std::endl;
}
}
else
{
bwrite = false;
msglog = msglog + "Canal BH2 Linea " + std::to_string(i) + "; ";
}
}/*Fin if Canal BH2*/
else if(canal == "BH6")
{
if (tmaline >= 453)
{
nuevoCliente->strCliente.plasticID=linea.substr(148,3);
nuevoCliente->strCliente.disenoImpresion=dameDisenoImpresion(impresion, linea.substr(148,3)+" "+bin);
nuevoCliente->strCliente.tipoImpresion=dameTipoImpresion(impresion, linea.substr(148,3)+" "+bin);
std::string rfc = isRfcValido(linea.substr(440,13)); //RFC
//string rfc;
nuevoCliente->strCliente.tipoPer = rfc.substr(0, 2);
nuevoCliente->strCliente.rfcFinal = rfc.substr(2, (rfc.length()-2));
if(nuevoCliente->strCliente.tipoPer == ("PI"))
{
nuevoCliente->strCliente.tipoPer ="RFC INCORRECTO";
}
}
else
{
bwrite = false;
msglog = msglog + "Canal BH6 Linea " + std::to_string(i) + "; ";
}
}/*Fin if Canal BH6*/
else if (canal == "BHV")
{
if( tmaline >= 318 ){
if(linea.substr(101,12) !="00000000000 ")
nuevoCliente->strCliente.saldoPromCompr = convierteCifras(linea.substr(101,12));
if(linea.substr(306,12)!="00000000000 ")
nuevoCliente->strCliente.saldoPromDispo = convierteCifras(linea.substr(306,12));
if(linea.substr(227,12)!="00000000000 ")
nuevoCliente->strCliente.saldoProm = convierteCifras(linea.substr(227,12));
if(linea.substr(164,12)!="00000000000 ")
nuevoCliente->strCliente.saldoPromDispMax = convierteCifras(linea.substr(164,12));
}
else{
bwrite = false;
msglog = msglog + "Canal BHV Linea " + std::to_string(i) + "; ";
}
}/*Fin if Canal BHV*/
}/*FIN DEL ELSE AL HD*/
}/*FIN DEL CICLO*/
file.close();
}/*FIN DEL IF OPEN*/
else
{
std::cout<<"ERROR!!! el archivo "<<path<<" no se pudo crear"<<std::endl;
}
delete(nuevoCliente);
std::cout<<"sale del extrae"<<std::endl;
// file.close();
return clientesF;
}/*FIN DEL EXTRAE*/
And in the main i have a for each loop that calls the extraction function for every single file read
enter code here
int main(int argc, char** args)
{
time_t now = time(0);
tm *ltm = gmtime(&now);
std::string shini = std::to_string(ltm->tm_hour)+":"+std::to_string(ltm->tm_min)+":"+std::to_string(ltm->tm_sec);
std::ofstream archivo;
archivo.open("/desarrollo/pruebasc++/pruebasJuan/Salida/tiempos.txt");
archivo<<shini<<std::endl;
/*----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
//comienza la prueba
Extraccion ex = {};
ManejaArchivos archivos{};
std::vector<Cliente> todosClientes;
std::vector<BanderaEnvio> banderasEnvio;
std::vector<CFD> CFDS;
std::vector<TIM> TIMS;
std::vector<CentroReparto> centrosReparto;
std::vector<DomiciliacionS702> domicilios;
std::vector<CargosEnAclaracion> cargos;
std::vector<CaracImpresion> impresiones;
std::vector<Journal> journals;
banderasEnvio.clear();
centrosReparto.clear();
impresiones.clear();
std::string pathENTR = "";
std::string pathJOUR = "";
int ppba = 1; /*1- Usa la ruta de Producción; 2- Usa nuestra ruta de prueba*/
if (ppba == 1)
{
pathENTR = "/NAS01/01.Ingenieria_NFS/08_Agosto";//args[0];//C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916";
pathJOUR = "/user1/BANAMEX/Salida_doc1/TDC_L6_ECS/08_Agosto";//args[1];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/jour";
}
else
{
pathENTR = "/desarrollo/pruebasc++/pruebasJuan/ENTR";//args[0];//C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916";
pathJOUR = "/desarrollo/pruebasc++/pruebasJuan/JOURNAL";//args[1];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/jour";
}
std::string pathMedioEnvio = "/NAS01/01.Ingenieria_NFS/08_Agosto/Medio_envio_Flag.TXT";//args[2];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/otros/Medio_envio_Flag.TXT";
std::string pathSalida = "/desarrollo/pruebasc++/pruebasJuan/Salida";//args[3];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/Salida";
std::string pathCentrRep = "/NAS01/01.Ingenieria_NFS/08_Agosto/catalogo_sepomex.txt";//args[4];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/otros/catalogo_sepomex.txt";
std::string pathImpresion = "/NAS01/01.Ingenieria_NFS/08_Agosto/ControlBanderas.txt";//args[5];//C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/otros/ControlBanderas.txt";
double pesoENTR = 0;
double pesoDOM = 0;
double pesoDISP = 0;
double pesoTIM = 0;
double pesoCFD = 0;
double pesoJOUR = 0;
double sumaPesos = 0;
double tiempo = 0;
std::vector<std::string> jours;
std::vector<std::string> entrs = archivos.getENTRS(pathENTR);
archivo<<"Nombres de archivos"<<std::endl;
int contadorIteraciones = 0;
if (entrs.size() >= 1 )
{
std::cout<<"Lee los Catalogos Medio_envio_Flag, BanderaEnvio y CaracImpresion"<<std::endl;
banderasEnvio = archivos.leerBanderaEnvio(pathMedioEnvio);
centrosReparto = archivos.leerCentroReparto(pathCentrRep);
impresiones = archivos.leerCaractImpresion(pathImpresion);
}
for(auto arch : entrs)
{
contadorIteraciones++;
archivo<<contadorIteraciones<<"--Procesando Archivo ENTR: "<<arch<<"----------------------------------------------"<<std::endl;
std::cout<<contadorIteraciones<<"--Procesando Archivo ENTR: "<<arch<<"-------------------------------------------------------------"<<std::endl;
std::cout<<" Procesando.... *"<<std::endl;
// //std::cout<<pathJOUR<<" -- antes del getJournals"<<std::endl;
jours = archivos.getJournals(pathJOUR, arch);
std::string pathUnJour = "";
for (auto jour : jours)
{
archivo<<" -Jour: "<<" -- "<<jour<<std::endl;
journals.clear();
journals = archivos.leeJournal(pathUnJour, jour);
pathUnJour = "";
}
std::string nombreCFD = archivos.archivoRelacionado(pathENTR, arch, "CFD");
if(nombreCFD != "" )
{
CFDS.clear();
CFDS = archivos.leeCFD(pathENTR, nombreCFD);
}
std::string nombreTIM = archivos.archivoRelacionado(pathENTR, arch, "TIM");
if(nombreTIM != "" )
{
TIMS.clear();
TIMS = archivos.leeTIM(pathENTR, nombreTIM);
}
std::string nombreDomiciliacion = archivos.getArchivotS702(pathENTR, arch);
std::string nombreDisp = archivos.getArchivoEPSTDISP(pathENTR, arch);
domicilios.clear();
domicilios = archivos.leerDomiciliacion(pathENTR);
cargos.clear();
cargos = archivos.leerCargosAclaracion(pathENTR);
std::string pathArchivo = pathENTR + "/" + arch;
todosClientes.clear();
todosClientes = ex.extrae(pathArchivo, journals, banderasEnvio, CFDS, TIMS, centrosReparto, domicilios, cargos, impresiones);
archivos.generaArchivo(pathSalida, todosClientes, arch);
std::cout<<" Procesando.... +"<<std::endl;
}
time_t tfin = time(0);
ltm = gmtime(&tfin);
std::string shfin = std::to_string(ltm->tm_hour) + ":" + std::to_string(ltm->tm_min) + ":" + std::to_string(ltm->tm_sec);
archivo<<shfin;
archivo.close();
return 0;
}
by the way, i use a linux base server to compile, thank you everyone!

How can I plug this C++ memory leak?

I have a program that is giving the expected output, however I am receiving the following errors below my output"
* glibc detected * PathFinder2: free(): invalid pointer: 0xb6046b70 ***
I run my program using Valgrind. However i do not have a file called pthread_create.c or pthread_create.c.
How can I troubleshoot the error based on these stats by Valgrind:
==3439== 800 bytes in 1 blocks are definitely lost in loss record 100 of
103
==3439== at 0x402ADFC: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3439== by 0x80560B5: Assignm3::Maze::InitMazeArray() (in /home/a/Desktop/PathFinder2)
==3439== by 0x8055167: Assignm3::Maze::LoadMaze(std::string) (in /home/a/Desktop/PathFinder2)
==3439== by 0x804A1F8: solveMaze(void*) (in /home/a/Desktop/PathFinder2)
==3439== by 0x4052F6F: start_thread (pthread_create.c:312)
==3439== by 0x42A170D: clone (clone.S:129)
Update
Is there logic error in this part which lead to memory leak. I cant seem to find anything wrong.
static void *solveMaze(void *vptr_args)
{
Point point1, point2, point3;
int nxtPx, nxtPy;
mazeObj->LoadMaze();
point1 = mazeObj->getStartLocation();
point3 = mazeObj->getEndLocation();
VectorOfPointStructType Path, vecMain;
Path.push_back(point1);
vecMain.push_back(point1);
point2 = mazeObj->getEndLocation();
nxtPx = point1.getX();
nxtPy = point1.getY();
sleep(3);
while (true)
{
string thread1, thread2;
thread1 = THREAD_NAMES[line1];
thread2 = THREAD_NAMES[line2];
cout << "Thread " << THREAD_NAMES[line1] << " is running" << endl;
cout << "Thread " << THREAD_NAMES[line2] << " is running" << endl;
for (int x = 0; x < 5; x++)
{
if (thread1 != THREAD_NAMES[line1] && thread2 != THREAD_NAMES[line2])
{
cout << "Thread " << THREAD_NAMES[line1] << " is running" << endl;
cout << "Thread " << THREAD_NAMES[line2] << " is running" << endl;
}
if (x == 0)
{
nxtPx++;
point3 = Point(nxtPx, nxtPy);
if ((mazeObj->IsThereBarrier(point3) || mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3, ob))
{
Path.push_back(point3);
vecMain.push_back(point3);
ob.push_back(point3);
if (mazeObj->IsThereBarrier(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToBarrier(pthread_self(), Path))
{
sleep(1);
}
pthread_mutex_unlock(&mutex1);
}
else if (mazeObj->IsThereDanger(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToDangerArea(pthread_self(), Path))
{
if (thread1 == THREAD_NAMES[line1])
{
diemsg1();
}
else if (thread2 == THREAD_NAMES[line2])
{
diemsg2();
}
create();
}
pthread_mutex_unlock(&mutex1);
}
nxtPx--;
Path.pop_back();
}
else if ((!mazeObj->IsThereBarrier(point3) && !mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3,
vecMain))
{
point1 = point3;
Path.push_back(point1);
vecMain.push_back(point1);
point3 = mazeObj->getEndLocation();
x = - 1;
if (point1.isConnected(point2) || reachEnd)
{
reachEnd = true;
break;
}
}
else
{
nxtPx--;
}
}
else if (x == 1)
{
nxtPy++;
point3 = Point(nxtPx, nxtPy);
if ((mazeObj->IsThereBarrier(point3) || mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3, ob))
{
Path.push_back(point3);
vecMain.push_back(point3);
ob.push_back(point3);
if (mazeObj->IsThereBarrier(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToBarrier(pthread_self(), Path))
{
sleep(1);
}
pthread_mutex_unlock(&mutex1);
}
else if (mazeObj->IsThereDanger(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToDangerArea(pthread_self(), Path))
{
if (thread1 == THREAD_NAMES[line1])
{
diemsg1();
}
else if (thread2 == THREAD_NAMES[line2])
{
diemsg2();
}
create();
}
pthread_mutex_unlock(&mutex1);
}
nxtPy--;
Path.pop_back();
}
else if ((!mazeObj->IsThereBarrier(point3) && !mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3,
vecMain))
{
point1 = point3;
Path.push_back(point1);
vecMain.push_back(point1);
point3 = mazeObj->getEndLocation();
x = - 1;
if (point1.isConnected(point2) || reachEnd)
{
reachEnd = true;
break;
}
}
else
{
nxtPy--;
}
}
else if (x == 2)
{
nxtPx--;
point3 = Point(nxtPx, nxtPy);
if ((mazeObj->IsThereBarrier(point3) || mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3, ob))
{
Path.push_back(point3);
vecMain.push_back(point3);
ob.push_back(point3);
if (mazeObj->IsThereBarrier(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToBarrier(pthread_self(), Path))
{
sleep(2);
}
pthread_mutex_unlock(&mutex1);
}
else if (mazeObj->IsThereDanger(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToDangerArea(pthread_self(), Path))
{
if (thread1 == THREAD_NAMES[line1])
{
diemsg1();
}
else if (thread2 == THREAD_NAMES[line2])
{
diemsg2();
}
create();
}
pthread_mutex_unlock(&mutex1);
}
nxtPx++;
Path.pop_back();
}
else if ((!mazeObj->IsThereBarrier(point3) && !mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3,
vecMain))
{
point1 = point3;
Path.push_back(point1);
vecMain.push_back(point1);
point3 = mazeObj->getEndLocation();
x = - 1;
if (point1.isConnected(point2) || reachEnd)
{
reachEnd = true;
break;
}
}
else
{
nxtPx++;
}
}
else if (x == 3)
{
nxtPy--;
point3 = Point(nxtPx, nxtPy);
if ((mazeObj->IsThereBarrier(point3) || mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3, ob))
{
Path.push_back(point3);
vecMain.push_back(point3);
ob.push_back(point3);
if (mazeObj->IsThereBarrier(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToBarrier(pthread_self(), Path))
{
sleep(2);
}
pthread_mutex_unlock(&mutex1);
}
else if (mazeObj->IsThereDanger(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToDangerArea(pthread_self(), Path))
{
if (thread1 == THREAD_NAMES[line1])
{
diemsg1();
}
else if (thread2 == THREAD_NAMES[line2])
{
diemsg2();
}
create();
}
pthread_mutex_unlock(&mutex1);
}
nxtPy++;
Path.pop_back();
}
else if ((!mazeObj->IsThereBarrier(point3) && !mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3,
vecMain))
{
point1 = point3;
Path.push_back(point1);
vecMain.push_back(point1);
point3 = mazeObj->getEndLocation();
x = - 1;
if (point1.isConnected(point2) || reachEnd)
{
reachEnd = true;
break;
}
}
else
{
nxtPy++;
}
}
else if (x == 4)
{
pthread_mutex_lock(&mutex1);
for (;;)
{
point1 = Path[Path.size() - 2];
nxtPx = point1.getX();
nxtPy = point1.getY();
point3 = Point(nxtPx - 1, nxtPy);
if (!pathObj->isLocationInPath(point3, vecMain))
{
x = 0;
Path.pop_back();
if (mazeObj->IsThereBarrier(point3))
{
point3 = mazeObj->getEndLocation();
}
pthread_mutex_unlock(&mutex1);
break;
}
point3 = Point(nxtPx, nxtPy + 1);
if (!pathObj->isLocationInPath(point3, vecMain))
{
x = - 1;
Path.pop_back();
if (mazeObj->IsThereBarrier(point3))
{
point3 = mazeObj->getEndLocation();
}
pthread_mutex_unlock(&mutex1);
break;
}
point3 = Point(nxtPx + 1, nxtPy);
if (!pathObj->isLocationInPath(point3, vecMain))
{
x = 2;
Path.pop_back();
if (mazeObj->IsThereBarrier(point3))
{
point3 = mazeObj->getEndLocation();
}
pthread_mutex_unlock(&mutex1);
break;
}
point3 = Point(nxtPx, nxtPy - 1);
if (!pathObj->isLocationInPath(point3, vecMain))
{
x = 1;
Path.pop_back();
if (mazeObj->IsThereBarrier(point3))
{
point3 = mazeObj->getEndLocation();
}
pthread_mutex_unlock(&mutex1);
break;
}
Path.pop_back();
}
pthread_mutex_unlock(&mutex1);
int deX = point1.getX();
int deY = point1.getY();
if (thread1 == THREAD_NAMES[line1])
{
time(&end);
cout << "Thread: " << THREAD_NAMES[line1] << " found the dead end at " << "[ " << deX << " , " << deY << " ]" << endl;
cout << "Time Elapsed: " << difftime(end, start) << " seconds" << endl;
}
else if (thread2 == THREAD_NAMES[line2])
{
time(&end);
cout << "Thread: " << THREAD_NAMES[line2] << " found the dead end at " << "[ " << deX << " , " << deY << " ]" << endl;
cout << "Time Elapsed: " << difftime(end, start) << " seconds" << endl;
}
}
else
{}
}
{
break;
}
}
Path.push_back(point2);
if (!submitPath)
{
submitMazeSolnObj->submitSolutionPath(pthread_self(), Path);
submitPath = true;
}
return NULL;
}
It seems that you have new[] without delete[] in Assignm3::Maze::InitMazeArray().

Password program

#include <iostream>
#include <string>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <cctype>
using namespace std;
int main()
{
fstream fin;
string password;
cout << "Please enter your password!" << endl;
cin >> password;
fin.open("Text.txt");
int nlen = password.length();
if (nlen <= 7)
return false;
if (nlen >= 8)
return true;
bool hasUpp = false;
bool hasLow = false;
bool hasDig = false;
bool hasSym = false;
for (int i = 0; i < nlen; i++)
{
if (isupper(password[i]))
hasUpp = true;
if (islower(password[i]))
hasLow = true;
if (isdigit(password[i]))
hasDig = true;
}
if (hasLow && hasUpp && hasDig && hasSym)
{
return true;
}
else
{
return false;
}
if (hasLow && hasUpp && hasDig && hasSym)
{
cout << "Your password is strong! " << endl;
}
else
{
cout << "Your password is too weak! " << endl;
}
cin.get();
cin.get();
return 0;
}
This program is supposed to take input data from a user and decide whether or not it is a somewhat strong password. I realize this is not near finished yet. The problem I am having is making the program read my input file and figure out whether or not any of the words in the input file are being entered as passwords, which would then tell them their password is bad.
I've made some modifications to your program to make it work at least with user input data. You propably wondered why you don't get any output from your program? There are two if-clauses within your program which will cause the main() function to return (= your application terminates):
if (nlen <= 7)
return false;
if (nlen >= 8)
return true;
One of the return statements is called since one of the if-clauses is always true and therefore your program will exit there.
Here is the modified code to process a single password entered by the user:
#include <iostream>
#include <string>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <cctype>
using namespace std;
int main()
{
string password;
cout << "Please enter your password!" << endl;
cin >> password;
int nlen = password.length();
bool hasUpp = false;
bool hasLow = false;
bool hasDig = false;
bool hasSym = false;
bool isLong = false;
if (nlen >= 8)
isLong = false;
for (int i = 0; i < nlen; i++)
{
if (isupper(password[i]))
hasUpp = true;
if (islower(password[i]))
hasLow = true;
if (isdigit(password[i]))
hasDig = true;
}
if (hasLow && hasUpp && hasDig && hasSym && isLong)
{
cout << "Your password is strong! " << endl;
}
else
{
cout << "Your password is too weak! " << endl;
}
cin.get();
cin.get();
return 0;
}
To extend this to read several passwords from a file, you have to read the file line by line (as explained here) and process each line.
**YOU CAN DO LIKE THIS**
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
void gotox(int x)
{
COORD xy = {0, 0};
xy.X = x;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy);
}
void getx(int &x) {
CONSOLE_SCREEN_BUFFER_INFO csbi;
if(GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
x = csbi.dwCursorPosition.X;
}
}
int main()
{
SetConsoleTitle("file password protector");
char pas;
string password = "";
int x,t = 0;
cout<<"enter password : ";
do
{
pas = _getch();
switch(int(pas))
{
case 8: getx(x);
if(x>17)
{
--x;
gotox(x);
cout<<" ";
if(password.length()>0){password.erase(password.length()-1,1);}
--t;
gotox(x);
}
break;
case 27: return 0;
case 13: if(t>8)
{
pass = 27
}
break;
default :if(t < 30)
{
if(int(pas)>0)
{
password.push_back(pas);cout<<"*";++t;
}
else
{
pas = _getch();
}
}}}while(pas != 13);
bool hasUpp = false;
bool hasLow = false;
bool hasDig = false;
bool hasSym = false;
for (int i = 0; i < t; i++)
{
if (isupper(password[i]))
hasUpp = true;
if (islower(password[i]))
hasLow = true;
if (isdigit(password[i]))
hasDig = true;
}
if (hasLow && hasUpp && hasDig && hasSym)
{
cout << "Your password is strong! " << endl;
}
else
{
cout << "Your password is too weak! " << endl;
}
_getch();
return 0;
}