【问题标题】:How to input multiple values from a txt file into an array C++如何将txt文件中的多个值输入到数组C++中
【发布时间】:2019-12-01 16:39:57
【问题描述】:

我希望将 .txt 文件的各个输入输入到我的数组中,其中每个输入由空格分隔。然后 cout 这些输入。如何将 .txt 文件中的多个值输入到我的数组中?

    int main()
{
    float tempTable[10];

    ifstream input;
    input.open("temperature.txt");

    for (int i = 0; i < 10; i++)
    {
        input >> tempTable[i];
        cout << tempTable[i];
    }

    input.close();

    return 0;
}

根据我在这里写的内容,我希望文件的输入按计划进行,每个值都输入 tempTable[i] 但是当运行程序时会输出极端数,即 -1.3e9。

温度.txt文件如下:

25 20 11.2 30 12.5 3.5 10 13

【问题讨论】:

  • 你还没有问过问题。
  • 如何将 .txt 文件中的多个值输入到我的数组中? 看起来您已经在这样做了。什么是你没想到的?
  • 如果这根本不起作用,可能您将文本文件放在错误的位置或命名与您想象的不同。
  • 您的代码不会检查或关心您的文件是否被实际读取或是否包含足够的值。我希望您的文件根本没有被读取。

标签: c++ arrays iostream


【解决方案1】:

您的文件包含 8 个元素,您迭代 10 次。

您应该使用vectorlist 并迭代while(succeded)

#include <vector>
#include <fstream>
#include <iostream>
int main()
{
    float temp;    
    std::ifstream input;
    input.open("temperature.txt");
    std::vector<float> tempTable;
    while (input >> temp)
    {
        tempTable.push_back(temp);
        //print last element of vector: (with a space!)
        std::cout << *tempTable.rbegin()<< " ";
    }
    input.close();
    return 0;
}

【讨论】:

    【解决方案2】:

    您可以使用 boost::split 或直接将描述符分配给变量

    std::ifstream infile("file.txt");
    
    while (infile >> value1 >> value2 >> value3) {
        // process value1, value2, ....
    }
    

    或者使用其他版本

    std::vector<std::string> items;
    std::string line;
    
    while (std::getline(infile, line)) {
        boost::split(items, line, boost::is_any_of(" "));
        // process the items
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      相关资源
      最近更新 更多