Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Read Numeric Data from a Text File in C++

For example, if data in an external text file is like this:

45.78   67.90   87
34.89   346     0.98

How can I read this text file and assign each number to a variable in c++? Using ifstream, I am able to open the text file and assign first number to a variable, but I don't know how to read the next number after the spaces.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    float a;
    ifstream myfile;
    myfile.open("data.txt");
    myfile >> a;
    cout << a;
    myfile.close();
    system("pause");
    return 0;
}

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int data[6], a, b, c, d, e, f;
    ifstream myfile;
    myfile.open("a.txt");

    for(int i = 0; i << 6; i++)
        myfile >> data[i];

    myfile.close();
    a = data[0];
    b = data[1];
    c = data[2];
    d = data[3];
    e = data[4];
    f = data[5];
    cout << a << "" << b << "" << c << "" << d << "" << e << "" << f << "
";
    system("pause");
    return 0;
}
Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

Repeat >> reads in loop.

#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
    std::fstream myfile("D:\data.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        printf("%f ", a);
    }

    getchar();

    return 0;
}

Result:

45.779999 67.900002 87.000000 34.889999 346.000000 0.980000

If you know exactly, how many elements there are in a file, you can chain >> operator:

int main(int argc, char * argv[])
{
    std::fstream myfile("D:\data.txt", std::ios_base::in);

    float a, b, c, d, e, f;

    myfile >> a >> b >> c >> d >> e >> f;

    printf("%f%f%f%f%f%f
", a, b, c, d, e, f);

    getchar();

    return 0;
}

Edit: In response to your comments in main question.

You have two options.

  • You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested only in specified value.
  • You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.

Edit: How to skip values in file

To choose the 1234th value, use the following code:

int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
    float tmp;
    myfile >> tmp;
}
myfile >> value;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...