如何从文本文件中读取字符串并将其双击到链接列表中

How to read strings and double from text file into link list

本文关键字:双击 列表 链接 串并 字符 文本 文件 读取 字符串      更新时间:2023-10-16

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

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不是有效的浮点值,因此读取失败。

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

  1. 不要使用operator>>()读取std::string,而是在使用std::ws跳过空白后使用std::getline()(关于如何正确执行这一操作,有很多重复的问题)
  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("nr")));
    std::string name;
    double      value;
    while (in >> name >> value) {
        std::cout << "name='" << name << "' value=" << value << "n";
    }
}