我编辑代码以澄清实际代码:
#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")
错误是一样的,我希望有人能在这个问题上帮我?
发布于 2022-09-06 07:12:06
在C++中,所有代码都必须在函数中。此外,所有C++程序都必须有一个名为main的函数。
此外,您的代码将文件打开两次,一次是在声明runtimeFile变量时,一次是在调用open时。您不觉得奇怪吗?您的代码中有两次文件名吗?不要打开两次文件。最后,虽然这不是一个错误,但没有必要关闭文件,这将自动发生。
把所有这些放在一起,你就有了一个合法的C++程序。
#include <fstream>
int main()
{
std::fstream runtimeFile("cmg_operations_runtime.txt" , std::ios::out);
runtimeFile << "tempVector[j]" << ";\t";
}编辑
一些真实的代码已经发布了。基于此,我将删除全局runtimeFile变量,并使其本地化为callHandler,如下所示
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;
}但是,我不太清楚最新发布的代码是如何导致所描述的错误的。
https://stackoverflow.com/questions/73617987
复制相似问题