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);
}
Related
I want to pause my program on the 0x32, 0x33 and 0x34 key and make it work again on the 0x31 key, how can I? I used this code to pause on the 0x32 key, it's working, but I can't get it back to work on the desired key
To summarize what #user4581301 suggested:
#include <conio.h>
...
if (GetAsyncKeyState(0x32) || GetAsyncKeyState(0x33) || GetAsyncKeyState(0x34)) {
while (_getch() != 0x31)
;
}
If your application is a console application, I implemented the function you want through loop. If it's a desktop application, you can refer to my code logic.
#include <iostream>
#include<cstdlib>
#include<time.h>
#include<Windows.h>
#include<conio.h>
using namespace std;
int main()
{
while (true) {
for (int i = 0; i < 5; ++i) {
if (GetAsyncKeyState(gun_keys[i]) && (gun != guns[i])) {
gun = guns[i];
system("cls");
gun_delay = GetTime(gun->rpm);
gun_index = 0;
break;
}
}
if (GetAsyncKeyState(VK_DELETE)) //Bind key, what close this program
{
ExitProcess(-1); //Exit Process
}
if (GetAsyncKeyState(MOUSEEVENTF_MOVE) < 0) {
if (!is_mouse_down) {
is_mouse_down = true;
if (gun != nullptr)
gun_index = 0;
}
if (gun != nullptr && gun_index != gun->len) {
mouse_event(MOUSEEVENTF_MOVE, long(gun->pattner[gun_index][0] * K), long(gun->pattner[gun_index][1] * K), 0, 0);
++gun_index;
Sleep(gun_delay);
continue;
}
}
else
is_mouse_down = false;
if (_kbhit())//Checks if there is currently keyboard input and returns a non-zero value if there is, or 0 otherwise
{
int ch = _getch();
if (ch == 0x32 || ch == 0x33 || ch == 0x34)
{
ch = _getch();//It waits for input and pauses the program
}
if (ch != 0x31)
{
while (true)
{
if (_kbhit())
{
int ch = _getch();
if (ch == 0x31) break;
}
}
}
fflush(stdin);//Clear the input buffer
}
Sleep(150);
}
return 0;
}
I'm coding a parser for my Arduinoproject. I have a long charArray that contains multiple "packages" in the form of:
# package beginns
adress
; seperating character
adress
; seperating character
command
; seperating character
data
* package ends
One input could be:
#A0001;B0001;A;2456;*#A0002;B0002;B;7615;*#A0003;B0003;C;8943;*
The goal is to write a Parser that takes a charArray and splits it at one char ('#') and than a second time with another char (';'). The problem is that the outer splitting is only done once and than stopps. I think it has something to do with the pointer, but don't know what to do.
My Code:
void setup() {
Serial.begin(9600);
char test[] = "#A0001;B0001;A;2456;*#A0002;B0002;B;7615;*#A0003;B0003;C;8943;*";
Serial.print("Test: ");
Serial.println(test);
Serial.println("--------------------");
parseCurrentStream(test);
Serial.println("-----------END_OF_CODE------------");
}
void parseCurrentStream(char* input){
int commandCount = getCountOfCharInString(input, '*');
package packageList[commandCount];
commandCount = 0;
char* piece = strtok(input, "#");
while (piece != NULL){
Serial.println(piece);
package pack = getPackage(piece);
printPackage(pack);
commandCount++;
piece = strtok(NULL, "#");
}
}
package getPackage(char* packageString){
Serial.println("---Start_Parsing---");
Serial.print("StringInput: ");
Serial.println(packageString);
bool corruptedData = false;
if(!isEndCharExisting(packageString)){
corruptedData = true;
}
// final Fields
char* receiver;
char* transmitter;
char command;
char* data;
bool empty;
char* piece = strtok(packageString, ";");
int counter;
while (piece != NULL && !corruptedData){
Serial.print(corruptedData);
Serial.print(" | Piece ");
Serial.print(counter);
Serial.print(": ");
Serial.println(piece);
switch(counter){
case 0:
if(strlen(piece) == 5){
receiver = piece;
} else {
corruptedData = true;
}
break;
case 1:
if(strlen(piece) == 5){
transmitter = piece;
} else {
corruptedData = true;
}
break;
case 2:
if(strlen(piece) == 1){
command = piece[0];
} else {
corruptedData = true;
}
break;
case 3:
if(strlen(piece) == sizeOfCommand(command)){
data = piece;
} else {
corruptedData = true;
}
break;
case 4:
if(!(strlen(piece) == 1 && piece[0] == '*')){
corruptedData = true;
}
break;
default:
corruptedData = true;
break;
}
counter++;
piece = strtok(NULL, ";");
}
struct package finalPackage;
if(corruptedData){
finalPackage = {receiver, transmitter, command, data, true};
} else {
finalPackage = {receiver, transmitter, command, data, false};
}
Serial.println("---End_Parsing---");
return finalPackage;
}
Output:
Test: #A0001;B0001;A;2456;*#A0002;B0002;B;7615;*#A0003;B0003;C;8943;*
--------------------
A0001;B0001;A;2456;*
---Start_Parsing---
StringInput: A0001;B0001;A;2456;*
0 | Piece 0: A0001
0 | Piece 1: B0001
0 | Piece 2: A
0 | Piece 3: 2456
0 | Piece 4: *
---End_Parsing---
Package:
A0001
B0001
A
2456
0
-----------------
-----------END_OF_CODE------------
You can see that for the first iteraton it works perfectly, but the second "string" (#A0002;B0002;B;7615;*) is not parsed...
When i'm not using my function getPackage() the substrings are printed as expected. I have found some advice to copy the char before inserting it to the function but this also didn't help.
char pieceCopy[strlen(piece)];
strcpy(pieceCopy, piece);
Because you are splitting for different tokens at the same time (both in parseCurrentStream and in getPackage), you are messing up the internal state of strtok. However, using one strtok_r for each tokenization, you can provide a pointer to a char pointer, that each different strtok_r can use to save its current state. See the example in the link provided. strtok_r is especially useful in multi-threaded environments.
char *strtok_r(char *str, const char *delim, char **saveptr);
char input[] = "the quick brown fox";
char* token;
char* rest;
char* str = input;
while ((token = strtok_r(str, " ", &rest))) {
str = NULL;
printf("%s\n", token);
}
Thanks for all of your support!!!
For me the solution of #Gerhardh worked perfectly.
The strsep() was availbale for me.
My code looks like this now:
void parseCurrentStream(char* input){
int commandCount = getCountOfCharInString(input, '*');
char* piece;
char* string;
string = strdup(input);
while( (piece = strsep(&string,"#")) != NULL ){
if(strlen(piece) > 0){
package pack = getPackage(piece);
printPackage(pack);
}
}
}
package getPackage(char* packageString){
Serial.println("---Start_Parsing---");
Serial.print("StringInput: ");
Serial.println(packageString);
bool corruptedData = false;
// final Fields
char* receiver;
char* transmitter;
char command;
char* data;
bool empty;
//char* piece = strtok(packageString, ";");
int counter = 0;
char* piece;
char* string;
string = strdup(packageString);
while ((piece = strsep(&string,";")) != NULL){
Serial.print(corruptedData);
Serial.print(" | Piece ");
Serial.print(counter);
Serial.print(": ");
Serial.println(piece);
switch(counter){
case 0:
if(strlen(piece) == 5){
receiver = piece;
} else {
corruptedData = true;
}
break;
case 1:
if(strlen(piece) == 5){
transmitter = piece;
} else {
corruptedData = true;
}
break;
case 2:
if(strlen(piece) == 1){
command = piece[0];
} else {
corruptedData = true;
}
break;
case 3:
if(strlen(piece) == sizeOfCommand(command)){
data = piece;
} else {
corruptedData = true;
}
break;
case 4:
if(!(strlen(piece) == 1 && piece[0] == '*')){
corruptedData = true;
}
break;
default:
corruptedData = true;
break;
}
counter++;
}
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
I have this error in my code, here is the code:
`
#pragma once
#include <WinSock2.h>
#include <Windows.h>
#include "TriviaServer.h"
#include "Validator.h"
#define PORT 8820
#define IFACE 0
#include <algorithm>
using namespace std;
TriviaServer::TriviaServer()
{
_roomIdSequence = 0;
_socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_socket == INVALID_SOCKET)
throw std::exception(__FUNCTION__ " - socket");
/*DataBase Build*/
}
TriviaServer::~TriviaServer()
{
map<int, Room*>::iterator it = _roomsList.begin();
for (it; it != _roomsList.end(); it++)
{
delete it->second;
}
map<SOCKET, User*>::iterator it2 = _connectedUsers.begin();
for (it2; it2 != _connectedUsers.end(); it2++)
{
delete it2->second;
closesocket(it2->first);
}
closesocket(_socket);
}
void TriviaServer::server()
{
bindAndListen();
thread handleMessages(&TriviaServer::handleRecievedMessages);
handleMessages.detach();
while (true)
{
cout << "accepting client..." << endl;
accept();
}
}
void TriviaServer::bindAndListen()
{
struct sockaddr_in sa = { 0 };
sa.sin_port = htons(PORT);
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = IFACE;
if (::bind(_socket, (struct sockaddr*)&sa, sizeof(sa)) == SOCKET_ERROR)
throw std::exception(__FUNCTION__ " - bind");
cout << "binded" << endl;
if (::listen(_socket, SOMAXCONN) == SOCKET_ERROR)
throw std::exception(__FUNCTION__ " - listen");
cout << "listening..." << endl;
}
void TriviaServer::accept()
{
SOCKET client_socket = ::accept(_socket, NULL, NULL);
if (client_socket == INVALID_SOCKET)
throw std::exception(__FUNCTION__);
cout << "Client accepted !" << endl;
// create new thread for client and detach from it
std::thread tr(&TriviaServer::clientHandler, this, client_socket);
tr.detach();
}
void TriviaServer::clientHandler(SOCKET s)
{
bool clientConnected = true;
while (clientConnected)
{
int code = Helper::getMessageTypeCode(s);
RecievedMessage* m = buildRecieveMessage(s, code);
addRecievedMessage(m);
}
}
void TriviaServer::safeDeleteUser(RecievedMessage* m)
{
try
{
SOCKET soc = m->getSock();
handleSignout(m);
if (soc != NULL)
{
closesocket(soc);
}
}
catch (...)
{ }
}
void TriviaServer::addRecievedMessage(RecievedMessage* m)
{
std::unique_lock<std::mutex> locker(_mtxRecievedMessages);
m->setUser(getUserBySocket(m->getSock()));
locker.lock();
_queRcvMessages.push(m);
locker.unlock();
_cond.notify_one();
}
RecievedMessage* TriviaServer::buildRecieveMessage(SOCKET s, int code)
{
vector<string> values;
int len;
switch (code)
{
case SIGN_IN_REQUEST:
for (int i = 0; i < 2; i++)
{
len = Helper::getIntPartFromSocket(s, 2);
values.push_back(Helper::getStringPartFromSocket(s, len));
}
break;
case SIGN_OUT_REQUEST:
break;
case SIGN_UP_REQUEST:
for (int i = 0; i < 3; i++)
{
len = Helper::getIntPartFromSocket(s, 2);
values.push_back(Helper::getStringPartFromSocket(s, len));
}
break;
case AVAILABLE_ROOM_REQUEST:
break;
case ROOM_USERS_REQUEST:
case ROOM_JOIN_REQUEST:
values.push_back(Helper::getStringPartFromSocket(s, 4));
break;
case ROOM_LEAVE_REQUEST:
break;
case ROOM_CREATE_REQUEST:
len = Helper::getIntPartFromSocket(s, 2);
values.push_back(Helper::getStringPartFromSocket(s, len));
values.push_back(Helper::getStringPartFromSocket(s, 1));
values.push_back(Helper::getStringPartFromSocket(s, 2));
values.push_back(Helper::getStringPartFromSocket(s, 2));
break;
case ROOM_CLOSE_REQUEST:
break;
case EXIT_APPLICATION:
break;
}
RecievedMessage* m;
if (!values.empty())
{
m = new RecievedMessage(s, code, values);
}
else
{
m = new RecievedMessage(s, code);
}
return m;
}
void TriviaServer::handleRecievedMessages()
{
std::unique_lock<std::mutex> locker(_mtxRecievedMessages);
while (true)
{
if (_queRcvMessages.empty())
{
_cond.wait(locker);
}
switch (_queRcvMessages.front()->getMessageCode())
{
case SIGN_IN_REQUEST:
handleSignin(_queRcvMessages.front());
break;
case SIGN_OUT_REQUEST:
handleSignout(_queRcvMessages.front());
break;
case SIGN_UP_REQUEST:
handleSignup(_queRcvMessages.front());
break;
case AVAILABLE_ROOM_REQUEST:
handleGetRooms(_queRcvMessages.front());
break;
case ROOM_USERS_REQUEST:
handleGetUsersInRoom(_queRcvMessages.front());
break;
case ROOM_JOIN_REQUEST:
handleJoinRoom(_queRcvMessages.front());
break;
case ROOM_LEAVE_REQUEST:
handleLeaveRoom(_queRcvMessages.front());
break;
case ROOM_CREATE_REQUEST:
handleCreateRoom(_queRcvMessages.front());
break;
case ROOM_CLOSE_REQUEST:
handleCloseRoom(_queRcvMessages.front());
break;
case EXIT_APPLICATION:
handleSignout(_queRcvMessages.front());
break;
}
_queRcvMessages.pop();
}
}
User* TriviaServer::getUserBySocket(SOCKET s)
{
std::map<SOCKET, User*>::iterator it;
it = find(_connectedUsers.begin(), _connectedUsers.end(), s);
if (it != _connectedUsers.end())
{
return it->second;
}
else
{
return NULL;
}
}
User* TriviaServer::handleSignin(RecievedMessage* m)
{
int flag = true; // if wrong details
map<string, string>::iterator it;
map<SOCKET,User*>::iterator itConnected;
User* login = nullptr;
for (it = _dbUsers.begin(); it != _dbUsers.end(); it++)
{
if ((it->first) == ((*(m->getValues()))[0]) && (it->second) == ((*(m->getValues()))[1]))
{
flag = false;
login = new User(it->first, m->getSock());
for (itConnected = _connectedUsers.begin(); itConnected != _connectedUsers.end(); it++)
{
if (itConnected->second->getUsername() == login->getUsername())
{
delete login;
login = nullptr;
}
}
}
}
if (login)
{
Helper::sendData(m->getSock(), to_string(SIGN_IN_SUCCESS));
}
else if (flag)
{
Helper::sendData(m->getSock(), to_string(SIGN_IN_WRONG_DETAILS));
}
else
{
Helper::sendData(m->getSock(), to_string(SIGN_IN_USER_CONNECTED));
}
return login;
}
bool TriviaServer::handleSignup(RecievedMessage* m)
{
//[203##username##pass##email]
string user = (*m->getValues())[0];
string pass = (*m->getValues())[1];
string email = (*m->getValues())[2];
if (!Validator::isPasswordValid(pass))
{
Helper::sendData(m->getSock(), to_string(SIGN_UP_PASS_ILLEGAL));
return false;
}
if (!Validator::isUsernameValid(user))
{
Helper::sendData(m->getSock(), to_string(SIGN_UP_USERNAME_ILLEGAL));
return false;
}
//////////////////// TEMP CODE
map<string, string>::iterator it = _dbUsers.begin();
for (it; it != _dbUsers.end(); it++)
{
if (user == it->first)
{
Helper::sendData(m->getSock(), to_string(SIGN_UP_USERNAME_EXISTS));
return false;
}
}
_dbUsers.insert(pair<string, string>(user, pass));
//////////////////// END TEMP CODE
//////////////////// FUTURE CODE:
/*if (!DataBase::isUserExists(user))
{
Helper::sendData(m->getSock(), to_string(SIGN_UP_USERNAME_EXISTS));
return false;
}
if(!DataBase::addNewUser(user, pass, email))
{
Helper::sendData(m->getSock(), to_string(SIGN_UP_OTHER));
return false;
}
*/
Helper::sendData(m->getSock(), to_string(SIGN_UP_SUCCESS));
return true;
}
void TriviaServer::handleSignout(RecievedMessage* m)
{
User* u;
if (u = m->getUser())
{
map<SOCKET, User*>::iterator it = _connectedUsers.begin();
for (it; it != _connectedUsers.end(); it++)
{
if (it->first == u->getSocket())
{
delete it->second;
closesocket(it->first);
}
}
handleCloseRoom(m);
handleLeaveRoom(m);
//handleLeaveGame(m);
}
}
bool TriviaServer::handleCreateRoom(RecievedMessage* m)
{
User* curr = m->getUser();
if (curr)
{
vector<string>* values = m->getValues();
if (curr->createRoom(++_roomIdSequence, m->getUser(),(*values)[0] ,stoi((*values)[1], nullptr, 0), stoi((*values)[3], nullptr, 0), stoi((*values)[2], nullptr, 0)))
{
_roomsList.insert(pair<int, Room*>(_roomIdSequence, curr->getRoom()));
return true;
}
return false;
}
else
{
return false;
}
}
bool TriviaServer::handleCloseRoom(RecievedMessage* m)
{
}
bool TriviaServer::handleJoinRoom(RecievedMessage* m)
{
}
bool TriviaServer::handleLeaveRoom(RecievedMessage* m)
{
}
void TriviaServer::handleGetUsersInRoom(RecievedMessage* m)
{
}
void TriviaServer::handleGetRooms(RecievedMessage* m)
{
}
`
I tried to put comments on all the '==' and '!=' to search where is the problem but the error keep showing up.
it is in this cpp file, as far as i can tell from the code (the only file i can't compile)
thanks for the help,
sorry for the long code,
Omer
The problem was the order of the includes in other headers that included,
it should be
#include <WinSock2.h>
#include <Windows.h>
and not the other way around!
#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;
}