【问题标题】:Storing information in text file as variables in C++在 C++ 中将信息作为变量存储在文本文件中
【发布时间】:2013-03-07 17:56:43
【问题描述】:

我需要 C++ 从输入 文件中获取信息并将其存储为不同的变量 的帮助。格式如下。

us,northfields,Northfields,VA,9342,38.8042,-77.205

我该怎么做呢?

编辑:对不起,这是我第一次使用论坛。这是我目前所拥有的。

#include "city.h"

void readLineOfData( istream& in, string &country,  string &city, string &city2, 
    string &state, int &pop, string &lat, string &longi);

void output( ostream& out, string country, string city, string city2,
    string state, int pop, string lat, string longi );

void cities( istream& in, ostream& out )
{
    ifstream ("cities.txt");
    string country, city, city2, state, lat, longi;
    int pop;
    readLineOfData(in, country, city, city2, state, pop, lat, longi);
    while(!in.fail())
    {

        output( cout, country, city, city2, state, pop, lat, longi );


        readLineOfData(in, country, city, city2, state, pop, lat, longi);
    }
    return;
}

void readLineOfData( istream& in, string &country,  string &city, string &city2, 
    string &state, int &pop, string &lat, string &longi)
{
    getline( in, country, ',');
    getline( in, city, ',');
    getline( in, city2, ',');
    getline( in, state, ',');
    in >> pop;
    in.ignore( 200, ',' );
    getline( in, lat, ',');
    getline( in, longi, '\n' );

}

void output( ostream& out, string country, string city, string city2,
    string state, int pop, string lat, string longi )
{
    out << country << endl;
    out << city << endl;
    out << city2 << endl;
    out << state << endl;
    out << pop << endl;
    out << lat << endl;
    out << longi << endl;
}

目前我已经设置它来设置变量。我有一个有助于缩短代码的头文件。我现在需要能够识别最高人口,如果不使用数组,我将如何做到这一点?

【问题讨论】:

  • 这对 Stack Overflow 来说实际上不是一个好问题。您应该基本熟悉编程。无需成为专家,但您应该阅读过一些文档。为了让我们相信你已经走了这么远,你可以告诉我们你尝试了什么以及它是如何让你失望的。您应该能够更准确地指定问题:总是只有一行输入还是可能有很多?你知道具体有多少吗?任何字段中是否可以包含逗号或者, always 是分隔符?在这里给我们一些工作!

标签: c++ input format


【解决方案1】:

你不能把它们变成真正的变量,除非把它们写到源代码中。

您可以获得的最接近的方法通常是将它们存储在 std::mapstd::unordered_map 中,并将预期的“变量名”作为键。

【讨论】:

    【解决方案2】:

    试试这样的:

    std::vector<std::string> data;
    std::ifstream in("file.txt");
    std::string temp = "";
    for(std::istream_iterator<char> iter(in); in; ++iter) {
      if(*iter == ',') {
        data.push_back(temp);
        temp = "";
      }
      else {
        temp += *iter;
      }
    }
    

    然后您可以将不同的值作为data 缓冲区中的索引来访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多