【问题标题】:C++ Reading population records from a fileC ++从文件中读取人口记录
【发布时间】:2020-08-02 03:01:40
【问题描述】:

我正在尝试编写一个 C++ 程序,该程序从下面给出的文件中获取人口记录列表:

Jackson 49292
Levy 40156
Indian River 138894
Liberty 8314
Holmes 19873
Madison 19115

有没有好办法处理印第安河案?这是我当前编写的代码:

 ifstream file("county_data-5.txt");
  if(!file)
  {
    cout<<"\nError: File not found!\n";
  }
  else
  {
    string name ,string;
    double pop;
    while(!file.eof())
    {
      if(!file.eof())
      {
        //file>>name;
        //file>>pop;
        getline(file, string);
        stringstream ss(string);
        ss >> name >> pop;
        insert(root,name, pop);
      }
    }
  }
  file.close();

【问题讨论】:

  • 首先,您对!file.eof() 的使用是wrong,并且您应该检查读取是否成功在尝试使用读取的内容之前。
  • 我建议您阅读整行,然后尝试解析它们。例如,您可以找到最后一个空格,并将该行分成该位置的两个子字符串。
  • 如果可能,您能否在文本文件中使用不同的分隔符来分隔列,例如逗号?
  • 你应该解释一下当前代码做了什么,是否正确,如果不是,为什么不。

标签: c++ file istringstream


【解决方案1】:

有很多方法可以处理读取包含未知数量的空格分隔部分和尾随数字的名称。您可以使用cstdio 轻松做到这一点,并使用getline() 读取每一行,然后使用str.c_str() 的格式字符串" %[^0-9] %zu" 调用sscanf(),然后在分配给a 之前从temporary_name 修剪尾随空格字符串。

停留在当前时代的 C++ 中,您可以读取带有getline 的行,然后使用.find_first_of() 成员函数来定位字符串中的第一个数字。例如,您可以保留一个数字列表,例如const char *digits = "0123456789";,然后用line.find_first_of(digits); 定位第一个数字。知道第一个数字在哪里,然后您可以使用.substr() 成员函数复制name,然后从末尾去除尾随空格。

更大的考虑是如何存储所有读取的值。如果您创建一个简单的struct,其中包含成员std:string name; 和size_t pop;,那么您可以创建一个结构体std::vector,并使用.push_back() 成员函数添加从文件中读取的每个结构体数据,以添加一个将新结构添加到结构的向量中。

结构的简单实现可以是:

struct population
{
    std::string name;
    size_t pop;
    
    /* constructors */
    population() { name = ""; pop = 0; }
    population(const std::string& n, const size_t p) : name(n), pop(p) {}
};

为了简化从文件中读取,您可以创建&gt;&gt; 的重载,它将从打开的文件流中读取一行数据,并为您将name 和pop 分开。 &lt;&lt; 的第二个重载将允许您以您选择的合理格式输出结构。添加您将拥有的重载:

/* struct to hold name population, 
 * and overloads of operators >> and << to facilitate splitting name/hours.
 */
struct population
{
    std::string name;
    size_t pop;
    
    /* constructors */
    population() { name = ""; pop = 0; }
    population(const std::string& n, const size_t p) : name(n), pop(p) {}
    
    /* overloads of >> (separates name/pop) and << (outputs name/pop) */
    friend std::istream& operator >> (std::istream& is, population& p) {
        const char *digits = "0123456789";
        
        std::string line {};
        if (getline (is, line)) {                               /* read line */
            size_t popbegin = line.find_first_of(digits);       /* find 1st [0-9] */
            if (popbegin != std::string::npos) {                /* valdiate found */
                std::string tmp = line.substr(0, popbegin);     /* get name */
                while (isspace(tmp.back()))                     /* remove trailing */
                    tmp.pop_back();                             /* .. spaces */
                p.name = tmp;                                   /* assign to name */
                p.pop = stoul(line.substr(popbegin));           /* assign to pop */
            }
        }
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const population& p) {
        os << std::left << std::setw(32) << p.name << "  " << p.pop << '\n';
        return os;
    }
};

那么你在main() 中需要做的就是验证你有一个作为参数传递的文件名,打开文件并验证它是否可以读取(比如std::ifstream f),然后你的读取和值分离减少到一个简单的循环:

    population p {};    /* instance of population struct to facilitate read from file */
    std::vector<population> records {};         /* vector of population */
    
    while (f >> p) {                            /* read population data from file */
        records.push_back(p);                   /* add to population vector */
    }

现在您将所有位置和人口都存储在 struct records 的向量中。总而言之,您可以这样做:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>

/* struct to hold name population,  
 * and overloads of operators >> and << to facilitate splitting name/hours.
 */
struct population
{
    std::string name;
    size_t pop;
    
    /* constructors */
    population() { name = ""; pop = 0; }
    population(const std::string& n, const size_t p) : name(n), pop(p) {}
    
    /* overloads of >> (separates name/pop) and << (outputs name/pop) */
    friend std::istream& operator >> (std::istream& is, population& p) {
        const char *digits = "0123456789";
        
        std::string line {};
        if (getline (is, line)) {                               /* read line */
            size_t popbegin = line.find_first_of(digits);       /* find 1st [0-9] */
            if (popbegin != std::string::npos) {                /* valdiate found */
                std::string tmp = line.substr(0, popbegin);     /* get name */
                while (isspace(tmp.back()))                     /* remove trailing */
                    tmp.pop_back();                             /* .. spaces */
                p.name = tmp;                                   /* assign to name */
                p.pop = stoul(line.substr(popbegin));           /* assign to pop */
            }
        }
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const population& p) {
        os << std::left << std::setw(32) << p.name << "  " << p.pop << '\n';
        return os;
    }
};

int main (int argc, char **argv) {
    
    if (argc < 2) { /* validate 1 argument given for filename */
        std::cerr << "error: filename required as 1st argument.\n";
        return 1;
    }
    
    std::ifstream f (argv[1]);  /* open filename provided as 1st argument */
    
    if (!f.is_open()) { /* validate file is open for reading */
        std::cerr << "file open failed: " << argv[1] << '\n';
        return 1;
    }
    
    population p {};    /* instance of population struct to facilitate read from file */
    std::vector<population> records {};         /* vector of population */
    
    while (f >> p) {                            /* read population data from file */
        records.push_back(p);                   /* add to population vector */
    }
    
    for (const auto& loc : records)             /* output results */
        std::cout << std::left << std::setw(32) << loc.name << loc.pop << '\n';
}

使用/输出示例

在文件dat/population.txt 中使用您的数据,使用和结果将是:

$ ./bin/poprecords dat/population.txt
Jackson                         49292
Levy                            40156
Indian River                    138894
Liberty                         8314
Holmes                          19873
Madison                         19115

由于您将数据存储在结构向量中,因此您可以按照您喜欢的任何方式对向量进行排序以分析数据。

这只是解决问题的众多方法之一。如果您还有其他问题,请仔细查看并告诉我。

【讨论】:

    【解决方案2】:

    我想展示一个额外的解决方案,使用更现代的 C++ 元素。而且,我将使用regex 来描述什么是有效输入,什么是无效输入。

    使用正则表达式,您可以详细定义允许或不允许的内容。我们可以非常严格或允许前导和尾随空格,或多个空格或任何空白字符或任何我们想要的。因此,即使您有像 Holmes Region 1 19873 这样的县名,我们也可以将其视为有效并提取正确的数据。

    我不确定,如果你理解正则表达式。反正。我现在将为您的数据定义一个正则表达式。整个正则表达式是:

    ^\s*(\w+(\s+\w+)*)\s+(\d+)\s*$
    1      Begin of line
    \s*    Zero or more white spaces
    (      Begin of a group. Later we will extract this groupd data (the county name)
    \w+    One or more characters, a-z, A-Z and _ (First county sub name)
    (      Begin of optional group for county names with more sub names
    \s+    One or more whit spaces between county sub names
    \w+    One or more characters, a-z, A-Z and _ (additional county sub names)
    )      ENd of group for additional county subnames (always having starting white spaces)
    *      There may be 0 or more additionaly sub names for county
    \s+    One or more white spaces (in front of population count)
    (      Start of group for population count. Will be extracted later
    \d+    One or more digits (So, we will make sure that this is a valid number)
    )      End of Group for digits
    \s*    0 or more white spaces
    $      End of line
    

    所以,你看,我们可以为我们指定的目的定义一个正则表达式。

    至于程序结构的其余部分,一切都不是标准的方法。

    重要。在 C++ 中,我们将数据和相应的方法放在一个类中。这包括 IO 功能。因此,提取器运算符和插入器运算符。只有类应该知道如何读取和写入其数据。

    因此,我们将简单地定义一个只有 2 个数据成员的“CountyPopulation”类,并覆盖提取器和插入器运算符。

    在提取器中,我们将读取一个完整的行并将其与我们的正则表达式进行匹配。如果匹配,那么我们可以提取我们需要的 2 个组。很简单。

    对于驱动程序代码。我们将打开源文件并检查它是否可以打开。然后,我们使用 CTAD 定义一个std::vetcor 并使用它的范围构造函数来填充它。范围构造函数需要 2 个迭代器。为此,我们使用std::istream_iterator。整个构造将简单地为源代码行中的所有行调用我们类的提取器运算符。

    这导致将完整文件读入我们的std::vetcor 的一行代码。

    请看:

    `#include <iostream>
    #include <fstream>
    #include <string>
    #include <regex>
    #include <algorithm>
    #include <iomanip>
    
    struct CountyPopulation {
        // Our Data
        std::string county{};
        unsigned long population{};
    
        // Overwrite extractor
        friend std::istream& operator >> (std::istream& is, CountyPopulation& cp) {
            // Read a complete line
            if (std::string line{}; std::getline(is, line)) {
    
                // We want to evaluate the string using a regular expression
                std::smatch sm; std::regex re{ R"(^\s*(\w+(\s+\w+)*)\s+(\d+)\s*$)" };
    
                // If the string matches our patternm, then we can copy the data
                if (std::regex_match(line, sm, re)) {
                    cp.county = sm[1];
                    cp.population = std::stoul(sm[3]);
                }
                else std::cerr << "\n*** Error: Invalid Data in line:  '" << line << "'\n";
            }
            return is;
        }
        // Overwrite inserter
        friend std::ostream& operator << (std::ostream& os, const CountyPopulation& cp) {
            return os << std::left << std::setw(30) << cp.county << " --> " << cp.population << '\n';
        }
    };
    
    int main() {
        // Open file and check, if it could be opened
        if (std::ifstream countyFileStream{ "r:\\county_data-5.txt" }; countyFileStream) {
    
            // Define a vector and use its range constructor to read all values from the file
            std::vector population(std::istream_iterator<CountyPopulation>(countyFileStream), {});
    
            // Show all read data on screen
            std::copy(population.begin(), population.end(), std::ostream_iterator<CountyPopulation>(std::cout));
        }
        else std::cerr << "\n*** Error: Could not open source file\n";
        return 0;
    }
    

    使用 C++17 编译和测试

    【讨论】:

      【解决方案3】:

      正如 MikeCAT 在他的评论中指出的那样,while(!file.oef()) 是不对的。相反,您可以简单地执行while(file)。如果这些是人口记录,您可以使用int 而不是double。此外,if 语句是不必要的,因为您已经有一个 while 循环。您还应该更改 string 的名称以防止混淆。

      【讨论】:

      • 这个答案中似乎没有主要问题的答案(如何处理Indian River 138894 案例)。也可能不适合使用int。如果人口数据的单位是“千人”呢?
      • 我不认为它会是那样,而且我不确定 stringstream 是如何工作的,所以你可能想向后遍历字符串直到你碰到一个空格。
      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2016-09-16
      相关资源
      最近更新 更多