0

我正在尝试将一些文本写入文件,但在为 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;
}
4

1 回答 1

3

Your tofile is declared inside an if block (a single-statement one), so it only has the scope of that block. Move the declaration to where you declared the rest of your variables.

于 2013-11-12T18:25:02.720 回答