使用来自输入文件(字符串和整数)的数据并在循环中使用

Utilizing data from input file (string and int) and utilizing in loop

我必须创建一个程序,从输入文件中获取数据,并从中获取 returns 平均值和最大值(沸点和相关字符串 'substance')。来自给定输入文件的数据如下:

Acetaldehyde    20.8
Acetone     50.5
Acetylene   -84
Ammonia     -35.5
Aniline     184.4
Benzene     80.4
Chloroform  62.2
Ethane      -88
Ether       35
Furfurol    161.7
Glycerin    290
Glycerine   290
Naphthalene 218
Nitrobenzene    210.9
Petrol      95
Petroleum   210
Phenol      182
Propane     -43
Propylene   -47.7
Tar     300
Toluene     110.6
Turpentine  160
Water       100
Xylene      142.7

我知道加载输入数据的代码。但是,我不确定要从中提取什么数据。这是我到目前为止所拥有的:

int boiling, maximum=0,sum=0;
string substance;

///declare input stream variable
ifstream inData;

///open input file
inData.open("input.txt");

///Read the boiling temps
inData>>substance,boiling;

问题的第二部分是在 'for' 循环中使用输入文件中的 'string' 变量,因为我不确定还有什么可以用作循环的参数.我不知道该怎么做,如有任何解释,我们将不胜感激。

我确定我遇到了视野狭窄的情况,并且我的语法存在巨大问题,并且正在做一些完全明显错误的事情,但到目前为止我无法解决这个问题。如果有帮助,我们将在 class.

中讨论 'for' 循环

****编辑****

到目前为止:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
///declare variables
double boiling, maximum=0,sum=0;
string substance, substancemax;

///declare input stream variable
ifstream inData;

///open input file
inData.open("input.txt");

///Read the boiling temps
inData>>substance>>boiling;

cout<<"Common Chemicals & Substances:"<<endl;
cout<<left<<setw(10)<<"Substance"
    <<right<<setw(13)<<"Boiling Point"<<endl;
cout<<"--------------------------------------"<<endl;
cout<<left<<setw(10)<<substance
    <<right<<setw(13)<<boiling<<endl;
    ///run a loop w/ 'if' to read the data and calculate the minimum
while(inData)
{
    ///read temperature
    inData>>boiling;
    sum=sum+boiling;

        ///compare boiling with current maximum w/ 'if'
    if (boiling>maximum)
    {
        substancemax=substance;   ///update max substance
    }
}
///Display the data to the screen
cout<<fixed<<showpoint<<setprecision(2);
cout<<"\nThe average boiling point is "<<sum/24.0<<endl;
cout<<"\nThe substance with the highest BP is "<<substancemax<<endl;
cout<<"\nThe highest boiling point is "<<maximum<<endl;

///close the input file
inData.close();


    return 0;
    }

我仍然无法理解 'while' 语句的参数,可能还有其他问题。

********最终编辑************

我的程序使用 'for' 循环(我认为这是必需的,因为那是我们正在学习的章节)减去了它在沸点行中输出数字的事实。我不知道这个数字是从哪里来的

常见化学品和物质:

物质沸点

                1.48738e+103

乙醛 20.8 丙酮 50.5 乙炔-84 氨 -35.5 苯胺 184.4 苯 80.4 氯仿 62.2 乙烷-88 乙醚 35 糠醛 161.7 甘油290 甘油290 萘218 硝基苯 210.9 汽油 95 石油 210 苯酚182 丙烷-43 丙烯-47.7 Tar300 甲苯 110.6 松节油 160 水 100 二甲苯 142.7

平均沸点为109.95

BP最高的物质是Tar

最高沸点300.00

我的编码如下:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
///declare variables
double boiling, maximum=0,sum=0,counter=0;
string substance, substancemax;

///declare input stream variable
ifstream inData;

///open input file
inData.open("input.txt");

///Label for file
cout<<"Common Chemicals & Substances:"<<endl;
cout<<left<<setw(20)<<"Substance"
<<"Boiling Point"<<endl;
cout<<"--------------------------------------"<<endl;

    ///run a loop w/ 'if' to read the data and calculate the minimum
for(counter=0;counter<=24;counter++)
{
cout<<left<<setw(20)<<substance
    <<left<<boiling<<endl;

    ///read temperature
    inData>>substance>>boiling;
    sum=sum+boiling;

        ///compare boiling with current maximum w/ 'if'
    if (boiling>maximum)
    {
        maximum = boiling;          ///update max boiling temp
        substancemax=substance;   ///update max substance
    }
}
///Display the data to the screen
cout<<fixed<<showpoint<<setprecision(2);
cout<<"\nThe average boiling point is "<<sum/counter<<endl;
cout<<"\nThe substance with the highest BP is "<<substancemax<<endl;
cout<<"\nThe highest boiling point is "<<maximum<<endl;

///close the input file
inData.close();

    return 0;
    }

我不确定这个输出“1.48738e+103”是从哪里来的,也不知道如何消除它!

让我们看看我们是否可以 un-tunnel 狭隘的视野。你想找到具有最高沸点的物质(名称和温度),然后你想找到所有物质的平均沸点。为了保存最大沸点物质的名称,而沸点本身将取两个变量,如std::stringdouble,比如namemaxmax.

您还需要计算平均沸点。要计算平均值,您需要一个 double 来保存 sum,然后需要一个整数值来保存读取的沸点数。 (比如 size_t cnt = 0;

然后就是读取每个 nameboiling 点(应该分别是 std::stringdouble)当你循环读取 nameboiling,在你的循环中你想比较是否 boiling > max 如果是,更新 max = boiling;namemax = name; 以捕获物质和沸点作为新的最大值.您在每对 nameboiling 读取时更新计数器 cnt

当你的循环退出时,你有 namemaxmax 包含最高沸点的物质,所以剩下的就是计算平均沸点 sum / cnt

要将它们放在一起,请先声明变量并打开文件,例如

#include <iostream>
#include <fstream>
#include <string>

int main (int argc, char **argv) {

    if (argc < 2) {
        std::cerr << "error: insufficient arguments\n"
                << "usage: " << argv[0] << " filename\n";
        return 1;
    }

    double boiling, sum = 0, max = 0;
    size_t cnt = 0;
    std::string name, namemax;
    std::ifstream f(argv[1]);

现在循环读取每一行的 nameboiling注意:如何根据nameboiling的成功读取来控制读取循环,例如

    while (f >> name && f >> boiling) {
        sum += boiling;                   /* update sum with boiling */
        if (boiling > max) {              /* is boiling > max?, if so */
            max = boiling;                /* update max */
            namemax = name;               /* update namenax */
        }
        cnt++;                            /* increment counter */
    }

现在剩下的就是计算平均值并输出结果(您可以一次完成):

    std::cout << "average boiling pt. of " << cnt << " substances\n  "
            << sum / cnt
            << "\n\nsubstance with max boiling point\n  " << namemax
            << "  (" << max << ")\n";
}

完成!总而言之,你可以做到:

#include <iostream>
#include <fstream>
#include <string>

int main (int argc, char **argv) {

    if (argc < 2) {
        std::cerr << "error: insufficient arguments\n"
                << "usage: " << argv[0] << " filename\n";
        return 1;
    }

    double boiling, sum = 0, max = 0;
    size_t cnt = 0;
    std::string name, namemax;
    std::ifstream f(argv[1]);

    while (f >> name && f >> boiling) {
        sum += boiling;
        if (boiling > max) {
            max = boiling;
            namemax = name;
        }
        cnt++;
    }

    std::cout << "average boiling pt. of " << cnt << " substances\n  "
            << sum / cnt
            << "\n\nsubstance with max boiling point\n  " << namemax
            << "  (" << max << ")\n";
}

例子Use/Output

$ ./bin/boilingpt dat/boiling.txt
average boiling pt. of 24 substances
  108.583

substance with max boiling point
  Tar  (300)

将每行的输出相加

Per-your注释,还需要输出从文件中读取的每一个值。您可以在循环开始时执行此操作并简单地输出值。但是,让我们向您介绍 std::setw(),它允许您设置下一个输出的宽度(name),这样当您输出 boiling 时,它们将在一个漂亮的列中而不是交错来来回回。要使用 std::setw(),您只需提供宽度,例如std::setw(12) 适用于您的情况。 std::setw() 函数在 <iomanip> header 中,因此在顶部添加 #include <iomanip>

当您使用 std::setw() 时,您还想确保文本是 left-justified,因此我们也会在输出中包含 std::left。要以良好的方式输出每一行,您可以将上面的代码更改为:

#include <iomanip>
...
    std::cout << "substances and boiling points:\n";    /* output heading */
    while (f >> name && f >> boiling) {           /* read name/boiling pt */
        std::cout << "  " << std::setw(12) << std::left
                << name << "\t" << boiling << '\n';   /* output */
        sum += boiling;             /* add boiling to sum */
        if (boiling > max) {        /* is boiling > max, if so */
            max = boiling;          /* update max with boiling */
            namemax = name;         /* update namemax with name */
        }
        cnt++;      /* increment counter */
    }

    std::cout << "\naverage boiling pt. of " << cnt << " substances\n  "
            << sum / cnt
            << "\n\nsubstance with max boiling point\n  " << namemax
            << "  (" << max << ")\n";

(注意: 我也包括了最后的输出行,因为我在开头添加了一个 '\n' ,所以它将与你的列表分开 blank-line)

例子Use/Output

$ ./bin/boilingpt dat/boiling.txt
substances and boiling points:
  Acetaldehyde  20.8
  Acetone       50.5
  Acetylene     -84
  Ammonia       -35.5
  Aniline       184.4
  Benzene       80.4
  Chloroform    62.2
  Ethane        -88
  Ether         35
  Furfurol      161.7
  Glycerin      290
  Glycerine     290
  Naphthalene   218
  Nitrobenzene  210.9
  Petrol        95
  Petroleum     210
  Phenol        182
  Propane       -43
  Propylene     -47.7
  Tar           300
  Toluene       110.6
  Turpentine    160
  Water         100
  Xylene        142.7

average boiling pt. of 24 substances
  108.583

substance with max boiling point
  Tar  (300)

如果您在使用 std::setw(12) 后没有使用 std::left,则物质名称将是 right-justified(同样,看起来不错),例如

$ ./bin/boilingpt dat/boiling.txt
substances and boiling points:
  Acetaldehyde  20.8
       Acetone  50.5
     Acetylene  -84
       Ammonia  -35.5
       Aniline  184.4
       Benzene  80.4
    Chloroform  62.2
        Ethane  -88
         Ether  35
      Furfurol  161.7
      Glycerin  290
     Glycerine  290
   Naphthalene  218
  Nitrobenzene  210.9
        Petrol  95
     Petroleum  210
        Phenol  182
       Propane  -43
     Propylene  -47.7
           Tar  300
       Toluene  110.6
    Turpentine  160
         Water  100
        Xylene  142.7

average boiling pt. of 24 substances
  108.583

substance with max boiling point
  Tar  (300)

检查一下,如果您还有其他问题,请告诉我。