如何将多个值从 txt 文件输入到数组 C++ 中

How to input multiple values from a txt file into an array C++

提问人:Rawley Fowler 提问时间:12/2/2019 最后编辑:Rawley Fowler 更新时间:12/2/2019 访问量:856

问:

我希望将 .txt 文件的单个输入输入到我的数组中,其中每个输入都用空格分隔。然后输入这些输入。如何将 .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
C++ 数组 IOSTREAM

评论

0赞 Scott Hunter 12/2/2019
你还没有问过问题。
0赞 drescherjm 12/2/2019
如何将 .txt 文件中的多个值输入到我的数组中?看起来你已经在这样做了。你意想不到的是什么?
0赞 drescherjm 12/2/2019
如果这根本不起作用,也许你把你的文本文件放在错误的位置,或者它的名字与你想象的不同。
0赞 drescherjm 12/2/2019
您的代码不会检查或关心您的文件是否实际被读取,或者它是否包含足够的值。我希望您的文件根本没有被读取。

答:

0赞 camp0 12/2/2019 #1

您可以使用 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
}
1赞 SHR 12/2/2019 #2

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

您应该使用 or 和 迭代vectorlistwhile(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;
}