c++ - 如何从文本文件读取字符串和 double 到链接列表

标签 c++ string double ifstream

我想知道如何读取这个输入文件并存储它:

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

问题是它只读取前两行。我知道阅读的语法就好像它被分成列一样,但不是这样的。

最佳答案

读取字符串在第一个空格处停止。即阅读Stanta Fe进入字符串在 Santa 之后停止。如Fe不是有效的浮点值读数则失败。

该问题至少有两种解决方案:

  1. 而不是阅读 std::string使用operator>>()你会使用std::getline()使用 std::ws 跳过空格后(关于如何正确执行此操作有很多重复的问题)。
  2. 您将使用不考虑 ' ' 的流作为空白 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("\n\r")));
    std::string name;
    double      value;
    while (in >> name >> value) {
        std::cout << "name='" << name << "' value=" << value << "\n";
    }
}

关于c++ - 如何从文本文件读取字符串和 double 到链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34011172/

相关文章:

c++ - 如何在 C++ 中检查程序是否安装了 Qt

c++ - 创建 vector 序列 C++

c++ - FFmpeg 不关闭输出文件

java - Trim() 方法不删除文本前面的空格吗?

php - 将字符串转换为数组 PHP

c# - 将 double 四舍五入为整数

c++ - C++检测输入是否不满足条件

php - 为 div 中的每个数字添加边框

c# double 值显示为 .9999998?

c++ - 8 个字节如何容纳 302 个十进制数字? (欧拉挑战16)