退出我孤立的问题来验证码:函数调用多次导致程序与神秘的错误
#include <windows.h>
using namespace std;
const wchar_t* readLine(int posX, int posY, int len) {
wchar_t* wcharFromConsole = new wchar_t[len];
COORD pos = {posX,posY};
DWORD dwChars;
ReadConsoleOutputCharacterW(GetStdHandle(STD_OUTPUT_HANDLE),
wcharFromConsole, // Buffer where store symbols
len, // Read len chars
pos, // Read from row=8, column=6
&dwChars); // How many symbols stored
wcharFromConsole [dwChars] = L'\0'; // Terminate, so string functions can be used
return wcharFromConsole;
}
int main() {
for (int i = 0; i <= 63; i++) {
readLine(0,0,80);
}
system("pause");
}
的事情是,如果循环运行不到63倍它的工作原理,如果字符的长度从装控制台不到80这也适用...我不知道这里发生了什么。是否有任何资源我必须明确地关闭......但为什么,如果一个函数关闭了,它应该关闭它的所有资源。但是这里发生的事情我不知道,编译的程序(没有任何错误)在默默地退出system()
函数之前退出。还有其他的错误代码,因为我从我的项目中删除了部分代码,有时候是程序要求以不寻常的方式终止程序,而在其他时候程序被停止并停止接受键盘输入。
- 编辑:
我已经根据建议更新代码:
#include <iostream>
#include <windows.h>
using namespace std;
const wchar_t* readLine(int posX, int posY, int len) {
wchar_t* wcharFromConsole = new wchar_t[len];
COORD pos = {posX,posY};
DWORD dwChars = 0;
if(!ReadConsoleOutputCharacterW(GetStdHandle(STD_OUTPUT_HANDLE),
wcharFromConsole, // Buffer where store symbols
len, // Read len chars
pos, // Read from row=8, column=6
&dwChars)) // How many symbols stored
{
cout << "ReadConsoleOutputCharacterW failed, code" << GetLastError() << endl;
}
wcharFromConsole [dwChars] = L'\0'; // Terminate, so string functions can be used
return wcharFromConsole;
}
int main() {
for (int i = 0; i <= 100; i++) {
cout << "loop count: " << i << endl;
readLine(0,0,80);
}
system("pause");
}
输出:
loop count: 0
loop count: 1
loop count: 2
loop count: 3
// [...]
loop count: 63
loop count: 64
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
(第一个文档片断没有产生任何错误的所有)。
你没做的一件事是'''''''''''''''''''' – chris 2012-07-21 18:21:57
您是否考虑检查ReadConsoleOutputCharacterW和GetLastError的返回码? – 2012-07-21 18:24:49
@chris:如何删除函数中的变量,因为我必须返回它,而return是函数中执行的最后一个命令? – rsk82 2012-07-21 18:28:29