c++ - 如何将我的程序读入 C++ 中的平面文件?

标签 c++ visual-studio-2015

我正在用 C++ 构建一个小型物理引擎,它根据用户的一组发射参数(高度、角度、时间间隔和初始速度)发射弹丸,然后显示一些信息,例如总距离或角度它在空中的每个时间间隔,直到它撞到地面。只是为了让你看到,这是我的程序:

cout << "Insert a lanuch Angle (theta): ";  
cin >> thetaDegrees;    
cout << "Insert a launch height: ";     
cin >> yOld;            
cout << "Insert an initial velocity: ";     
cin >> initialVelocity;     
cout << "Time (DeltaT) in seconds: ";   
cin >> totalT;

for (double deltaTime = 0.0; deltaTime < totalT; deltaTime += 0.1) {

const double squared = deltaTime * deltaTime;       // squared constant for deltaTime squared

theta = thetaDegrees * PI / 180;    // converts theta to a degrees value

velocityX = initialVelocity * cos(theta);   // calculates Vx
velocityY = initialVelocity * sin(theta);   // calculates Vy

// apply initialV to velocity
velocity = initialVelocity + 9.8 * time;

xNew = xOld + velocity * time;  // works out displacement for X

yNew = yOld + velocity * deltaTime - gravitiyHalf / 0.5 * (squared);    // calculates Y

velocityY = velocity - 9.8 * deltaTime; // includes gravity to Y

angle = atan2(yNew, xNew) * 180 / PI;   // convert angle to degrees

cout << "\nHeight: " << yNew << endl;
cout << "Distance in Meters: " << xNew << "m" << endl;
cout << "Angle: " << angle << endl;
cout << "Time: " << deltaTime << "s " << endl;

if (heightCheck == false) {
    maxHeight = yOld;
    // keep maxheight equal to previous height
}

if (yNew < yOld && heightCheck == false) {
    heightCheck = true;
    // if projectile is going down, trigger maxheight
}

cout << "Maximum height:  " << maxHeight << endl;

if ((yNew < 0) || (deltaTime == totalT)) {
    getchar();      // stops if delta t = total T or projectile landed
}

yOld = yNew;    // refresh x & y
xOld = xNew;
}

在我的类(class)作业简报中,我被告知以下内容:

The software must be able to output two flat files so your work can be checked

所以我需要能够将我的程序输出到一个文件,这是什么意思,我该怎么做?

最佳答案

看看 fstream库,这是执行文件输入和输出的 C++ 标准方式。更具体地说,查看创建文件 std::fstream out( "output.txt", std::fstream::out ) , 并写入文件 std::string word = "some text"; out << word; .

使用 fstream,您可以将任何基本类型写入文件,因此您可以使用 out << number 写入普通数字(定点或 float ) , 它的工作原理与 std::cout 相同.

关于c++ - 如何将我的程序读入 C++ 中的平面文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835321/

相关文章:

visual-studio - Visual Studio 2015 安装程序被阻止

c# - Visual Studio Code Coverage 在 vNext 项目中过时了吗?

visual-studio-2015 - Visual Studio 在没有差异时显示差异

c++ - 如何绘制 UML 来说明在临界区工作的 2 个线程

c++ - boost asio : Is it possible to turn accepted tcp socket into basic_socket_iostream (or somehow get it from it)?

c++ - 实现递归冒泡排序时遇到栈溢出

c++ - MSVCP140.dll 丢失

c++ - 在 Visual Studio 2015 中检查 STL 容器

c++ - 使用 WinHTTP API 限制带宽使用的方法

c++ - 单个 MFC/Win32 控件似乎让我的整个桌面重绘