如何读取字符串并从文本文件加倍到链接列表

时间:2015-12-01 01:38:13

标签: 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;
}

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

1 个答案:

答案 0 :(得分:2)

读取字符串会在第一个空格处停止。也就是说,将Stanta Fe读入字符串会在Santa之后停止。由于Fe不是有效的浮点值读数,因此失败。

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

  1. 不是使用std::string阅读operator>>(),而是在使用std::getline()跳过空白后使用std::ws(关于如何正确地执行此操作,有很多重复的问题)。
  2. 您通过' '合适的imbue()方面使用不会将std::ctype<char>视为空格的流。对于这个问题,这是一个更有趣和非传统的解决方案。
  3. 鉴于教师不太可能在没有解释的情况下接受该解决方案,似乎可以为第二种方法提供代码:

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