【问题标题】:EDITED How do I split it up into char and int arrays已编辑如何将其拆分为 char 和 int 数组
【发布时间】:2019-12-01 21:45:58
【问题描述】:

我不知道帖子发生了什么,但它一定是在我第一次编辑时发生的。

当它位于单独的文件中时,我将这些信息输入并工作。但我需要它在一个文件中。
我查看了我的教科书和许多其他地方,但我找不到如何只从文件中获取文本或字符。 我已将所有信息放入一个数组中,但看起来我需要逐个提取每个组并将其放在我想要的位置,但这看起来很慢,乏味并且很容易出错。

Johnson 85 83 77 91 76 
Aniston 80 90 95 93 48 
Cooper 78 81 11 90 73  
Gupta 92 83 30 69 87   
Blair 23 45 96 38 59  
Clark 60 85 45 39 67   
Kennedy 77 31 52 74 83

Bronson 93 94 89 77 97 

Sunny 79 85 28 93 82  
Smith 85 72 49 75 63

如果这看起来很熟悉,这与我之前的帖子相同,现在我只需要弄清楚如何解析这些信息并再次使用它。

【问题讨论】:

  • 我什至会将这些信息放入一个数组并将单元格复制到正确的位置 -- 阅读您自己的问题,并假装您是正在研究这是怎么回事的人措辞。它是否描述了有关您正在阅读的结构的任何信息?
  • @PaulMcKenzie。我已经编辑了我的问题。它一定是在提交过程中搞砸了。

标签: c++


【解决方案1】:

您可能需要将输入作为字符串值并检查它以找到数字字符的开头。

只有在将输入字符串的字母部分与数字部分分开后,您才开始创建目标数组。

这可能会有所帮助:How can I check if a string has special characters in C++ effectively?

/e: 措辞

【讨论】:

    【解决方案2】:

    有多种方法可以做到这一点。您可以将其读入字符串并根据空格手动处理。或者您可以使用stringstream 将数值提取到array/vector。但是,这仍然需要您在执行此操作之前删除该名称。

    这是一个将文件内容读入unordered_map 的小代码,该unordered_map 本质上是其他语言中定义的dictionary

    void read_file(const std::string& path) {
      std::ifstream in(path); // file stream to read file
      std::unordered_map<std::string, std::vector<double>> map;
      /*
       * map structure to hold data, you do not have to use this.
       * I am using it only for demonstration purposes.
       * map takes string (name) as KEY and vector<double> as VALUE
       * so given a NAME you can get the corresponding grades VECTOR
       * i.e.: map["Johnson"] --> [85, 83, 77, 91, 76]
       */
    
      std::string line;
      while (std::getline(in, line)) { // read entire line
        if (line == "") continue; // ignore empty lines
        int last_alpha_idx = 0; // name ends when last alphabetic is encountered
        for (size_t i = 0; i < line.size(); i++)
          if (std::isalpha(line[i])) last_alpha_idx = i; // get index of last alpha
        std::string name = line.substr(0, last_alpha_idx + 1); // name is from index 0 to last_alpha_idx inclusive (hence +1)
        std::string numbers = line.substr(last_alpha_idx + 1); // array values the rest of the line after the name
        std::stringstream ss(numbers); // this is an easy way to convert whitespace delimated string to array of numbers
        double value;
        while (ss >> value) // each iteration stops after whitespace is encountered
          map[name].push_back(value);
      }
    }
    

    你可以把它读入一个数组,代码不会有太大的变化。我选择 string 作为 KEY 和 vector&lt;double&gt; 作为 VALUE 以形成字典(地图)的 KEY/VALUE 对。

    正如您在代码中看到的,它查找每行中的最后一个字母字符,并获取其索引以从读取的行中提取名称。然后它获取字符串的其余部分(只是数字)并将它们放入 stringstream 中,这将在其内部循环中单独提取每个数字。

    注意:上面的代码支持使用全名(例如“Johnson Smith 85 83 77 91 76”)。

    【讨论】:

      猜你喜欢
      • 2012-02-25
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      相关资源
      最近更新 更多