Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

c++ - 如何将txt文件中的多个值输入数组C ++(How to input multiple values from a txt file into an array C++)

I am looking to input individual inputs of a .txt file into my array where each input is separated by a space.

(我希望将.txt文件的各个输入输入到我的数组中,其中每个输入都用空格分隔。)

Then cout these inputs.

(然后找出这些输入。)

How do I input multiple values from the .txt file into my array?

(如何将.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;
}

With what I have written here I would expect an input of the file to go according to plan with each value entering tempTable[i] however when run the program out puts extreme numbers, ie -1.3e9.

(用我在这里写的内容,我希望文件的输入能够按计划进行,每个值都输入tempTable [i],但是在运行程序时,输入的数字为极值,即-1.3e9。)

The temperature.txt file is as follows:

(temperature.txt文件如下:)

25 20 11.2 30 12.5 3.5 10 13
  ask by Rawley Fowler translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your file contains 8 elements, you iterate 10 times.

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

You should use vector or list and iterate while(succeded)

(您应该使用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!)
        cout << *tempTable.rbegin()<< " ";
    }
    input.close();
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...