gpt4 book ai didi

c++ - Ofstream 对象不能使用 << 运算符 C++

转载 作者:行者123 更新时间:2023-11-28 00:38:37 25 4
gpt4 key购买 nike

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

最佳答案

您的 tofile 是在 if block (单语句 block )内声明的,因此它仅具有该 block 的范围。将声明移至声明其余变量的位置。

关于c++ - Ofstream 对象不能使用 << 运算符 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19936780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com