【问题标题】:Inputting values into an array from a file with C++使用 C++ 从文件中将值输入到数组中
【发布时间】:2019-02-27 14:02:47
【问题描述】:

文件确实打开了,我收到消息“文件打开成功”。但是,我无法将文件“random.csv”中的数组中的数据输入到我的 inputFile 对象中。

random.csv 中的数据为:

Boston,94,-15,65

Chicago,92,-21,72

Atlanta,101,10,80

Austin,107,19,81

Phoenix,112,23,88

Washington,88,-10,68

这是我的代码:

#include "main.h"

int main() {

    string item; //To hold file input
    int i = 0;
    char array[6];
    ifstream inputFile;
    inputFile.open ("random.csv",ios::in);

    //Check for error
    if (inputFile.fail()) {
        cout << "There was an error opening your file" << endl;
        exit(1);
    } else {
        cout << "File opened successfully!" << endl;
    }

    while (i < 6) {
        inputFile >> array[i];
        i++;
    }

    for (int y = 0; y < 6; y++) {
        cout << array[y] << endl;
    }


    inputFile.close();

    return 0;
}

【问题讨论】:

  • while (i &lt; 6) 目的?
  • 提示:char array[6] 只能容纳 5 个字符(每个 1 个字节)
  • 不要忘记字符数组应该以 null 结束!
  • 更好:不要将 char 的数组用于 C++ 中的字符串。使用std::string
  • @CinCout 一个大小为 6 的字符数组可以容纳 6 个字符。是什么让你觉得有什么不同? OPs 程序中不需要 nul 终止符。

标签: c++ arrays file input


【解决方案1】:

您好,欢迎来到 Stack Overflow (SO)。您可以使用std::getline() 从文件中读取每一行,然后使用boost::split() 将每一行拆分为单词。为每一行创建一个字符串数组后,您可以使用自己喜欢的容器来存储数据。

在下面的示例中,我使用了一个 std::map 来存储字符串和一个整数向量。使用地图还将使用键值对入口进行排序,这意味着最终容器将按字母顺序排列。实现非常基础。

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
#include <ctype.h>

typedef std::map<std::string,std::vector<int>> ContainerType;

void extract(ContainerType &map_, const std::string &line_)
{
    std::vector<std::string> data;

    boost::split(data, line_, boost::is_any_of(","));

    // This is not the best way - but it works for this demo.
    map_[data[0]] = {std::stoi(data[1]),std::stoi(data[2]),std::stoi(data[3])};
}

int main()
{
    ContainerType map;

    std::ifstream inputFile;
    inputFile.open("random.csv");

    if(inputFile.is_open())
    {
        std::string line;
        while( std::getline(inputFile,line))
        {
            if (line.empty())
                continue;
            else
                extract(map,line);
        }
        inputFile.close();
    }

    for (auto &&i : map)
    {
        std::cout<< i.first << " : ";
        for (auto &&j : i.second)
            std::cout<< j << " ";
        std::cout<<std::endl;
    }
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 2011-05-05
    相关资源
    最近更新 更多