首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fstream包含在标题中,但不工作吗?

fstream包含在标题中,但不工作吗?
EN

Stack Overflow用户
提问于 2022-09-06 07:07:44
回答 1查看 57关注 0票数 0

我编辑代码以澄清实际代码:

代码语言:javascript
复制
#include <fstream>
#include <iostream>

#include <ros/ros.h>
#include <rosbag/bag.h>
#include <std_msgs/Int32.h>
#include <std_msgs/String.h>
#include <nav_msgs/Odometry.h>

std::ofstream runtimeFile("cmg_operations_runtime.txt" , std::ios::out);

  

 void callhandler(const nav_msgs::Odometry::ConstPtr& msg)
{
   runtimeFile.open();
if (!runtimeFile)
        {
            std::cout << "cmg_operations_runtime.txt could not be opened.";
        }
         runtimeFile << "tempVector[j]" << ";\t";
         runtimeFile.close ();

        std::cout << "Runtime data stored." << std::endl;
 
}


int main(int argc, char **argv)
{
    ros::init(argc, argv, "main");
    ros::NodeHandle nh;
    ros::Subscriber Listener = nh.subscribe<nav_msgs::Odometry>("/odom", 100, callhandler);
  
    ros::spin();

    return 0;
}

错误:‘’运行时文件‘没有命名类型9\\ runtimeFile.open ("cmg_operations_runtime.txt")

错误是一样的,我希望有人能在这个问题上帮我?

EN

回答 1

Stack Overflow用户

发布于 2022-09-06 07:12:06

在C++中,所有代码都必须在函数中。此外,所有C++程序都必须有一个名为main的函数。

此外,您的代码将文件打开两次,一次是在声明runtimeFile变量时,一次是在调用open时。您不觉得奇怪吗?您的代码中有两次文件名吗?不要打开两次文件。最后,虽然这不是一个错误,但没有必要关闭文件,这将自动发生。

把所有这些放在一起,你就有了一个合法的C++程序。

代码语言:javascript
复制
#include <fstream> 

int main()
{
    std::fstream runtimeFile("cmg_operations_runtime.txt" , std::ios::out);
    runtimeFile << "tempVector[j]" << ";\t";
}

编辑

一些真实的代码已经发布了。基于此,我将删除全局runtimeFile变量,并使其本地化为callHandler,如下所示

代码语言:javascript
复制
void callhandler(const nav_msgs::Odometry::ConstPtr& msg)
{
    std::ofstream runtimeFile("cmg_operations_runtime.txt" , std::ios::out);
    if (!runtimeFile)
    {
        std::cout << "cmg_operations_runtime.txt could not be opened.";
    }
    runtimeFile << "tempVector[j]" << ";\t";
    std::cout << "Runtime data stored." << std::endl;
}

但是,我不太清楚最新发布的代码是如何导致所描述的错误的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73617987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档