首页 > 解决方案 > 为初学者阅读 C++ 文件所需的建议

问题描述

我有一个包含一些文本的文件,如下所示:

 Grey Heights 300 
22 White Road 400
100 Abbey Close 820

每行的第一个数字是街道号码,然后是街道名称,最后是每月租金。我正在尝试将此信息读入类型类的数组中。我无法弄清楚如何分离和检测句子的不同部分。有没有人有任何将句子中的文本分类为不同变量的经验,你有什么建议给我吗?目前,我正在使用 GETLINE 方法读取行,该方法工作正常,它似乎像我想要的那样丢弃了空格,但我正在努力处理文本文件的某些行,这些行只显示房屋名称而不是数字。

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

class cSquare { //declares a new class called cSquare
public: //declares all members as public
string SquareName; //first and only member of the cSquare class called square name
string getSquareName() const; //class method to output the contents of SquareName
void setSquareName(string); //class method to input into the variable SquareName
friend istream & operator >> (istream & is, cSquare & s); //sets a friend to allow the use of >>
};

// square name set method
void cSquare::setSquareName(string sname)
{
SquareName = sname;
}

//square name get method
string cSquare::getSquareName() const
{
return SquareName;
}

ostream & operator << (ostream & os, const cSquare & s) //friend 

{
os << s.getSquareName() << ' ';
return os;
}

istream & operator >> (istream & is, cSquare & s) //friend 
{
is >> s.SquareName;
return is;
}

int main()
{
string discard;
int i = 0; //counter
const int MAX_SIZE = 26; //declares a constant to store the size of the array - this will not chance 
so it is ok to be a const
ifstream monopoly("monopoly.txt", ios::in); //reads file in as a read only file
if (monopoly.is_open()) //checks if the file is open
{
    cSquare myArray[MAX_SIZE]; //declares the array of the object cSquare class

    getline(monopoly, discard); //allows it to be read line by line 
    string sname; //string to store what I read in from my file

    while (i < MAX_SIZE && monopoly >> sname) //inputs the contents of the file into the string sname
    {
        myArray[i].setSquareName(sname);//stores the string read in into the array
        cout << myArray[i].getSquareName(); //it outputs what is stored in the array here
        i++; //adds one each time to the i counter
    }

    }
}

标签: c++arraysclassifstream

解决方案


推荐阅读