如何从文本文件中读取字符串并将其双击到链接列表中
How to read strings and double from text file into link list
我想知道如何读取这个输入文件并存储它:
Tulsa
129.50
Santa Fe
70.00
Phoenix
110.00
San Diego
88.50
Yakama
150.25
这是我的cpp
#include <iostream>
#include "q2.h"
#include <string>
#include <fstream>
using namespace std;
int main()
{
fstream in( "q2input.txt", ios::in );
string loc;
double price;
while(fin >> loc >> price)
{
cout << "location: " << loc<< endl;
cout << "price: " << price << endl;
}
return 0;
}
问题是它只读取前两行。我知道阅读的语法,就好像它被分为几列一样,但不是这样。
读取字符串会在第一个空白处停止。也就是说,在Santa
之后停止将Stanta Fe
读取到字符串中。由于Fe
不是有效的浮点值,因此读取失败。
这个问题至少有两种解决方案:
- 不要使用
operator>>()
读取std::string
,而是在使用std::ws
跳过空白后使用std::getline()
(关于如何正确执行这一操作,有很多重复的问题) - 您可以使用一个不将
' '
视为空白的流,通过imbue()
创建一个合适的std::ctype<char>
方面。这是一个更有趣和非传统的问题解决方案
考虑到教师不太可能在没有解释的情况下接受该解决方案,提供第二种方法的代码似乎是可以的:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <locale>
#include <string>
struct ctype_table {
std::ctype_base::mask table[std::ctype<char>::table_size];
template <int N>
ctype_table(char const (&spaces)[N]): table() {
for (unsigned char c: spaces) {
table[c] = std::ctype_base::space;
}
}
};
struct ctype
: private ctype_table
, std::ctype<char>
{
template <int N>
ctype(char const (&spaces)[N])
: ctype_table(spaces)
, std::ctype<char>(ctype_table::table)
{
}
};
int main()
{
std::ifstream in("q2input.txt");
in.imbue(std::locale(std::locale(), new ctype("nr")));
std::string name;
double value;
while (in >> name >> value) {
std::cout << "name='" << name << "' value=" << value << "n";
}
}
相关文章:
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- C++,Qt:仅在双击后编辑qtablewidget项目
- 双击更改 mfc 中列表控件中的行的颜色
- C++MFC编辑框处理双击
- 双击滑块手柄时如何发出信号
- C/C++ 检测双击 TVItem 的常用控件
- 在使用 c++ 的 win32 api 中,我想跟踪双击和三次单击等
- 在树状视图中双击后焦点丢失
- MFC功能区主页按钮双击关闭应用程序
- QGraphicsScene 中的 QPushButton 需要双击而不是单击
- 处理WM_POINTER消息时,如何检测双击/点击
- 不典型地插入双连接列表
- 试图用c++编写我自己的链表实现,在点击列表中的3个元素后编写segfault代码
- 逆转具有值的双关联列表
- 双击编译C++ Unix 可执行文件不会打开现有文件以从中读取信息
- QListWidget 项目单击和项目双击 - 如果双击,则阻止单击
- 可执行文件无法在双击执行时创建新文件
- 使用构造函数初始化指向双击列表中NULL的指针
- 如何从文本文件中读取字符串并将其双击到链接列表中
- 如何在双击列表中插入编辑控件中的项目