【发布时间】:2016-03-17 12:32:36
【问题描述】:
我想出了一个提高词汇量的想法。这个想法是在一个文件中包含大量最常见的英语单词。 然后我会编写一个程序,一次在屏幕上显示一个单词。如果我识别出这个单词,我按向下键 移动到下一个单词,否则我按“S”将这个单词保存到一个名为 Unknown.txt 的文本文件中。
当我完成时,我将收集所有我不知道其含义的单词。如果我停在这里,并手动浏览每个单词 并用我的字典搜索它的含义,这将需要很多时间来学习它们。
但是,如果我有一种方法可以以编程方式保存单词的含义, 我可以轻松打开文件并立即了解单词的含义。这就是我想要实现的目标。
“10kword.txt”文件如下所示:
购买
客户
活跃
回应
练习
硬件。
这是我目前的代码:
#include <stdio.h>
#include <Windows.h>
void cls(void *hConsole);
int main(void)
{
FILE *inp, *out;
if (fopen_s(&inp, "10kWords.txt", "r")) {
fprintf(stderr, "Unable to open input file\n");
return 1;
}
else if (fopen_s(&out, "Unknown.txt", "a")) {
fprintf(stderr, "Error opening file Unknown.txt\n");
fclose(inp);
return 1;
}
char buf[100];
void *hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
while (1) {
//Press the down key to move to the next word
if (GetAsyncKeyState(VK_DOWN) == -32767) {
cls(hConsole);
fscanf_s(inp, "%s", buf, 100);
printf("%s", buf);
}
//Press S to save the word to output file
else if (GetAsyncKeyState('S') == -32767) {
fprintf(out, "%s\n", buf);
//Obtain word meaning from dictionary Programatically HERE and print it to 'out'
}
else if (GetAsyncKeyState(VK_ESCAPE)) {
break;
}
}
fclose(inp);
fclose(out);
return 0;
}
void cls(void *hConsole)
{
COORD coordScreen = { 0, 0 }; // home for the cursor
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD dwConSize;
// Get the number of character cells in the current buffer.
if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
{
return;
}
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
// Fill the entire screen with blanks.
if (!FillConsoleOutputCharacter(hConsole, // Handle to console screen buffer
(TCHAR) ' ', // Character to write to the buffer
dwConSize, // Number of cells to write
coordScreen, // Coordinates of first cell
&cCharsWritten))// Receive number of characters written
{
return;
}
// Get the current text attribute.
if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
{
return;
}
// Set the buffer's attributes accordingly.
if (!FillConsoleOutputAttribute(hConsole, // Handle to console screen buffer
csbi.wAttributes, // Character attributes to use
dwConSize, // Number of cells to set attribute
coordScreen, // Coordinates of first cell
&cCharsWritten)) // Receive number of characters written
{
return;
}
// Put the cursor at its home coordinates.
SetConsoleCursorPosition(hConsole, coordScreen);
}
【问题讨论】:
-
与您的问题无关,但不要使用前导下划线后跟大写字母的符号名称(例如您的变量
_Buf)。这些名称是为“实现”(即编译器和标准库)保留的。也不要像-32767一样使用magic numbers。如果要检查特定位或位,请使用位运算符。 -
我在第 22 行收到此警告;
main.cpp(22): warning C4473: 'fscanf_s' : not enough arguments passed for format string. -
不要忽略警告,它们是编译器表示你做错事或危险的方式。您收到警告是因为您没有为函数提供足够的参数,这将导致未定义的行为。你应该read a
fscanf_sreference。 -
我不明白你在问什么。我可以在您的代码中看到一些错误。
-
我不明白你想从我们这里得到什么。问题不清楚。文本中唯一的问题是,“有人可以帮我解决这个问题吗?”你到底想要什么?并且代码中有错误。它编译的事实并不意味着它是正确的。例如,您对
GetAsyncKeyState的使用是非常错误的。