gpt4 book ai didi

c++ - C++ 中的简单文件 I/O - 从不退出此循环?

转载 作者:行者123 更新时间:2023-11-30 04:39:34 25 4
gpt4 key购买 nike

我是第二门 OOP 类(class)的编程学生,我的第一门类(class)是用 C# 教授的,而这门类(class)是用 C++ 教授的。为了熟悉 C++,我们的教授要求我们用文件 I/O 编写一个相当大的程序。问题是,我的程序中有一小部分不起作用,至少对我来说不起作用。该项目要求我们编写一个循环来测试是否可以成功打开文件,而我编写的循环似乎不起作用。

我没有收到任何编译器错误,但是当我输入文件路径时,无论是相对路径还是绝对路径,它都说它无效。我感觉它与我在 do-while 循环中的条件有关,但我无法确定它。

我并不想把我的作业带到 SO,但我已经挠头了两个多小时,我似乎无法弄清楚。

你介意帮我解决我的循环吗?也许解释一下我做错了什么?我想学习。

谢谢!

代码:

Rainfall rData;
ifstream actualReader;
ifstream averageReader;
string aRDataLoc;
char response = 'a';
const int KILL_VALUE = 1;
double actualRainfallD;
double actualRainfallPassedArray[ARRAY_CAPACITY];
double averageRainfallPassedArray[ARRAY_CAPACITY];
int i = 0;

do
{
actualReader.clear();
cout << "\nPlease enter in the path to the file containing the actual rainfall data." << endl;
cout << "Path to file: ";
cin >> aRDataLoc;
actualReader.open(aRDataLoc.c_str());
if (!actualReader.is_open())
{
cout << "Invalid file path! Would you like to enter in a new file path?(y/n): ";
cin >> response;
if (response == 'n') { exit(KILL_VALUE); }
}
}while (!actualReader.is_open() && response == 'y');

最佳答案

我不知道您给 cin 的输入是什么,但请注意 cin 将在它遇到的第一个空白字符处停止。例如,如果您将以下内容作为输入:

C:\Program Files\directory

然后 aRDataLog 将具有值 C:\Program

为了阅读整行,你可以使用 getline .

同时检查 this post .

关于c++ - C++ 中的简单文件 I/O - 从不退出此循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2189577/

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