编写程序来分析文件

时间:2013-03-09 03:35:23

标签: c++

我正在编写一个代码,用于分析具有未知行数的输入文件。每条线的格式为“国家,城市,城市,州,人口,纬度,经度”。我目前收到一个错误,我的代码设置最小和最大的人口。错误说“左操作数必须是左值”。我试着查看,但找不到答案。

#include "city.h"
#include <iostream>
#include <fstream>
#include <string>

using std::string;
using std::ifstream;
using std::istream;
using std::ostream;
using std::cout;
using std::endl;
using std::getline;

void readLineOfData( istream& in, ostream& out, string &country,  string &city, string &city2, 
    string &state, int &pop, string &lat, string &longi);

void output( ostream& out, string country, string city, string city2,
    string state, int pop, string lat, string longi );

void cities( istream& in, ostream& out )
{
    ifstream ("cities.txt");
    string country, city, city2, state, lat, longi;
    int pop;
    readLineOfData(in, country, city, city2, state, pop, lat, longi);
    while(!in.fail())
    {

        output( cout, country, city, city2, state, pop, lat, longi );


        readLineOfData(in, country, city, city2, state, pop, lat, longi);
    }
    return;
}

void readLineOfData( istream& in, string &country,  string &city, string &city2, 
    string &state, int &pop, string &lat, string &longi)
{
    getline( in, country, ',');
    getline( in, city, ',');
    getline( in, city2, ',');
    getline( in, state, ',');
    in >> pop;
    in.ignore( 200, ',' );
    getline( in, lat, ',');
    getline( in, longi, '\n' );

}

void output( istream& in, ostream& out, string country, string city, string city2,
    string state, int pop, string lat, string longi )
{
    int smallestPop = 0;
    int largestPop = 0;
    string smallestCity;
    string largestCity;

    cout << country << endl;
    cout << city << endl;
    cout << city2 << endl;
    cout << state << endl;
    cout << pop << endl;
    cout << lat << endl;
    cout << longi << endl;

        if (pop < smallestPop || smallestPop == 0)
        {
            smallestPop = pop;
            smallestCity = city;
        }

        if (pop > largestPop || largestPop == 0)
        {
            largestPop = pop;
            largestCity = city;
        }

        out << "Smallest City: " << smallestCity << endl;
        out << "Population: " << smallestPop << endl;
        out << endl;
        out << "Largest City: " << largestCity << endl;
        out << "Largest Population: " << largestPop << endl;

}

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

您在多个表达式中使用=而不是==

if (pop < smallestPop || smallestPop = 0)

if (pop > largestPop || largestPop = 0)

所以你做的是作业而不是比较。由于operator precedence,我们看到此错误。由于<||在第一种情况下的优先级高于=,因此我们最终得到:

((pop > smallestPop) || smallestPop) = 0

分配给lvalue。如果另一方面你有这个:

 if ( pop < smallestPop || (smallestPop = 0) )

程序编译得很好,因为括号会导致作业首先发生。避免注释中提到的这些类型问题的一种简单方法是将常量放在左侧。虽然我喜欢这种解决方案,但很多开发人员都不喜欢这种非传统的符号。

答案 1 :(得分:0)

从查看代码快速猜测。我看到报告“左操作数必须是左值”的常见情况是,当您在尝试比较相等性(C ++和许多其他语言中的“==”)时意外使用“=”(赋值)运算符时