我正在尝试将一些文本写入文件,但是在为ofstream类定义对象之后,我得到的错误是';'我曾经在哪里使用<<运算符写入文件。我正在使用Visual Studio 2012。
这是一个简单的端口扫描程序(使用cplusplus引用),如果用户想要获取日志文件,则write_check变量会提示用户。
#include <iostream>
#include <SFML/Network.hpp>
#include<fstream>
using namespace std;
bool port_open(const string& address, int port)
{
sf::TcpSocket socket;
bool open = (socket.connect (sf::IpAddress(address), port)==sf::Socket::Done);
socket.disconnect();
return open;
}
int main()
{ string address;
int port, check, in_port, fin_port;
char write_check;
cout<<"Press 1 for single port and 2 to check the range of ports.";
cin>>check;
switch(check)
{case 1:
{
cout<<"Enter the ip address of the client: ";
std::cin>>address;
cout<<"Enter the port to scan: ";
cin>>port;
if(port_open(address, port))
cout<<"The port "<<port<<" at IP:"<<address<<" is OPEN."<<endl;
else
cout<<"The port "<<port<<" at IP:"<<address<<" is CLOSED.";
break;
}
case 2:
{
cout<<"Enter the ip address of the client: ";
cin>>address;
cout<<"Enter the port from where scanning has to be started ";
cin>>in_port;
cout<<"Enter the port upto which scanning has to be done. ";
cin>>fin_port;
cout<<"Would you like to have the log in text file? y/n";
cin>>write_check;
if (write_check=='y')
std::ofstream tofile ("Log.txt");
for(int j=in_port; j<=fin_port; j++)
{
cout<<"Scanning port "<<j<<" on IP "<<address<<"...\n";
if (write_check=='y')
tofile <<"Scanning port "<<j<<" on IP "<<address<<"...\n"; //ERROR a ';' is expected (after tofile)
if(port_open(address, j))
{
cout<<" OPEN."<<endl;
if (write_check=='y')
tofile<<"OPEN."<<endl; //ERROR a ';' is expected (after tofile)
}
else
{
cout<<" CLOSED."<<endl;
if (write_check=='y')
tofile<<"CLOSED."<<endl; //ERROR a ';' is expected (after tofile)
}
}
break;}
}
system("pause");
return 0;
}
答案 0 :(得分:3)
您的tofile
在if
块(单个语句块)中声明,因此它只具有该块的范围。将声明移动到您声明其余变量的位置。