首页 > 解决方案 > 利用输入文件(字符串和整数)中的数据并在循环中利用

问题描述

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

乙醛 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
焦油 300
甲苯 110.6
松节油 160
水 100
二甲苯 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”变量,因为我不确定还有什么可以用作循环的参数。我不知道如何去做,任何解释都将不胜感激。

我确定我有一个隧道视觉的案例和我的语法有一个巨大的问题,并且正在做一些完全且明显错误的事情,但到目前为止我无法解决这个问题。如果有帮助,我们将在课堂上讨论“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

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 二甲苯 142.7

平均沸点为109.95

BP最高的物质是焦油

最高沸点为 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”来自哪里或如何消除它!

标签: c++stringfor-loopinputint

解决方案


让我们看看我们是否不能取消隧道视野。您想找到具有最大沸点的物质(名称和温度),然后您想找到所有物质的平均沸点。为了保存具有最大沸点的物质的名称,沸点本身将采用两个变量, asstd::string和 a double,比如说namemaxand max

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

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

当您的循环退出时,您拥有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]);

现在循环读取每一行的nameand boiling注意:如何根据和 的成功读取来控制读取循环 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";
}

示例使用/输出

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

substance with max boiling point
  Tar  (300)

添加每行的输出

根据您的评论,您还需要输出从文件中读取的每个值。您可以在循环开始时执行此操作并简单地输出值。但是,让我们向您介绍一下,std::setw()它允许您设置下一个输出的宽度 (the name),这样当您输出时,boiling它们将位于一个漂亮的列中,而不是来回交错。要使用std::setw(),您只需提供宽度,例如std::setw(12)将适用于您的情况。std::setw()函数在标题<iomanip>中,所以加起来#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'在开头添加了一个,所以它将与您的列表用一个空行分隔)

示例使用/输出

$ ./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::left在 using 之后没有使用std::setw(12),则物质名称将是右对齐的(再次,看起来不错),例如

$ ./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)

如果您还有其他问题,请仔细查看并告诉我。


推荐阅读