2013-02-27 137 views
3

我在Visual C++中編寫代碼以訪問串行端口。下面錯誤:預計聲明

代碼給出: -

#include<stdio.h> 
#include<cstring> 
#include<string.h> 
#include<conio.h> 
#include<iostream> 
using namespace std; 
//#include "stdafx.h" 
#ifndef __CAPSTONE_CROSS_SERIAL_PORT__ 
#define __CAPSTONE_CROSS_SERIAL_PORT__ 
HANDLE hSerial= CreateFile(L"COM1", GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); 

if(hSerial==INVALID_HANDLE_VALUE) 
{ 
if(GetLastError()==ERROR_FILE_NOT_FOUND){ 
//serial port does not exist. Inform user. 
} 
//some other error occurred. Inform user. 
} 

在上面的代碼,我在行收到錯誤在如果

if(hserial==INVALID_HANDLE_VALUE) 

誤差如下: -

Error:expected a declaration 

我得到同樣的錯誤在兩個大括號}如果聲明

我想知道爲什麼我收到這個錯誤到底如何解決它

+0

您在隨機地方編寫代碼。這不應該是在一個方法或類或什麼? – 2013-02-27 04:12:54

+0

除此之外,你需要'#include '。而且你所擁有的大部分支持代碼都是不需要的或者完全錯誤的。你不能指望科學怪人能夠正常工作,而不是使用C++。你需要一些基本的瞭解。 – 2013-02-27 06:01:16

回答

5

我想你可能需要閱讀this。問題在於您試圖在只有聲明有效的命名空間範圍(全局命名空間)處使用if語句。

你需要將你的邏輯包裝在某種功能中。

void mySuperCoolFunction() 
{ 
    if(hSerial==INVALID_HANDLE_VALUE) 
    { 
    if(GetLastError()==ERROR_FILE_NOT_FOUND) 
    { 
     //serial port does not exist. Inform user. 
    } 
    //some other error occurred. Inform user. 
    } 
}