gpt4 book ai didi

c++ - 打开一个文件程序 w/while 循环 C++

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

下面是我创建一个 while 循环以打开名为“G:/points.dat”的文件的说明

到目前为止,这是我的代码。我正在努力创建读取文件的 for 循环,将它们打印到监视器,然后使用这些整数作为 x、y 点。我可以理解命名 x 和 y 参数,但我正在为循环本身而苦苦挣扎

#include "Window.h"
#include "Colours.h"
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main(int argc, char * argv[]) {
// create a new window of size 500 x 500 pixels
// the top left corner of the window is (0,0)
SPA::Window window(500,500,"My Test");
ifstream myInputFile;
string inputFileName = "G:/points,dat";

myInputFile.open(inputFileName);

int i = 0;
myInputFile >> i;

myInputFile.close();

window.show(argc,argv);

return Fl::run();
}
  • 打开文件‘G:/points.dat’

  • 读入多对数字——即每行两个数字,直到文件结束

  • 您应该使用 while 循环和适当的文件状态测试来检测文件结束

  • eof 标志只有在您尝试读取文件末尾以外的至少一个值后才会设置为真。
  • 每对数字代表要绘制的直线上一点的 x 和 y 坐标 (x,y)。
    • 在你的循环中,为你读入的每个 (x,y) 值在当前行添加一个点

最佳答案

循环很简单

while (myInputFile >> x >> y)
{
// do something with x and y
...
}

该循环并没有严格地每行读取两个值,它只读取接下来的两个值,无论它们是否在下一行。

顺便说一句,你的代码中有错别字

string inputFileName = "G:/points,dat";

应该是

string inputFileName = "G:/points.dat";

当您打开一个文件时,您应该始终检查它是否打开成功。

关于c++ - 打开一个文件程序 w/while 循环 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833076/

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