gpt4 book ai didi

c++ - ifstream 不从 C++ 文件中读取值

转载 作者:太空宇宙 更新时间:2023-11-04 14:17:57 26 4
gpt4 key购买 nike

我是 C++ 的新手,目前正在上大学的 CS 类(class),但由于我的代码无法从我的输入文件“OH-in.dat”中读取值,所以我陷入了困境。此外,当涉及到哨兵值时,我不太清楚该怎么做(因为我需要一个 do while 循环,我想我只需要让哨兵值成为我采用的第一个值,然后简单地停止循环从那时起。)

这是我目前的代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
// Declare the variables to be used in the program.

ifstream infile;
string schoolname, location;
int tuition, enrollnum, i;
double average;

//Obtain the values for the variables from the file given.

infile.open("OH-in.dat"); //Accomplish task 1.
{
i = 0;
cout << "Schools in Cincinnati with tuition below $20,000." << endl;
cout << "-----------------------------------------------------" << endl;
do
{
// Read the values in the data file.
infile >> schoolname;
infile >> location;
infile >> enrollnum;
infile >> tuition;

// Separate the values that contain Cincinnati and if it's tuition is over 20000 dollars.

if (schoolname == "Cincinnati" && tuition < 20000)
{
cout << schoolname << " $" << tuition << endl;
i++;
}
// Display the number of schools that fit the criteria.
cout << "Number of schools: " << i << endl;
}
//While the 1st value read in is not ***, the loop will continue.
while (schoolname != "***");
//Close the file.
infile.close();
}
system("pause");
return 0;
}

这是我要输入的前四个值。

安条克学院

黄泉

330

27800

...

终于到了这个地步。

'* * *'

此数据是从 petersons.com 收集的

10 月 10 日和 11 日。一些名称和位置

数据已被更改。


现在,我在这段代码中遇到的两个主要问题是简单地让 C++ 读入值,其次让代码不无限地重复自身。

最佳答案

你可以使用类似的东西

if (infile.fail()) break;

紧接在四个“infile >>”语句之后。或者,如果您愿意,可以使用 .eof() 而不是 .fail() 。无论哪种方式,它都会在 infile 没有更多数据可提供时退出循环。

在您的特定情况下,当然,您正在寻找哨兵而不是文件的结尾,但同样的原则也适用。这是 C++ 的 break 语句的理想情况。

顺便说一下,一旦添加了break,您可能就不再需要do-while了。 while(true)for(;;)——即条件总是通过的循环——可能会起作用。这个循环的自然导出点在中间,在您将添加到它的中断处。

关于c++ - ifstream 不从 C++ 文件中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9764240/

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