-1

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

#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;

}

任何帮助,将不胜感激。

4

2 回答 2

2

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

if (pop < smallestPop || smallestPop = 0)

和:

if (pop > largestPop || largestPop = 0)

所以你正在做一个分配而不是一个比较。由于运算符优先级,我们看到了这个错误。由于两者<||都比第一种情况具有更高的优先级=,我们最终得到:

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

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

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

该程序将编译得很好,因为括号会导致分配首先发生。如评论中所述,避免此类问题的一种简单方法是将常量放在左侧。尽管我喜欢这种解决方案,但许多开发人员对这种非传统表示法犹豫不决。

于 2013-03-09T03:40:14.920 回答
0

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

于 2013-03-09T03:40:01.320 回答