c++ - 为初学者阅读 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
}
}
}
解决方案
推荐阅读
- javascript - HTML 按钮单击在新选项卡中打开 2 个链接
- javascript - Webpack 配置问题:图标字体在“构建”模式下不起作用
- python - Python:尽管没有任何此类包,但仍显示未满足的依赖项错误和损坏的包错误
- python - 从时间点列表中随机选择时间帧作为元组
- reactjs - type="text/babel" 的外部脚本不起作用
- python - 请求失败:Google 在 pytrends 库中返回了代码 429 的响应
- reactjs - React.render() 与 React Virtual Dom 有什么关系
- python - TableauServerClient 无法让 PDF 刷新
- python - 根据列表中的值提取列值
- multithreading - 互斥锁在这个问题中是如何工作的?