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
314 views
in Technique[技术] by (71.8m points)

visual c++ - Reading numbers from a space delimited text file in C++

I'm trying to read a file "parameters.txt" from the working directory.

This is parameters.txt:

1.0 1.0 1.0 1.0 3.14159 1.57079 0.001 10.0

I want to input each of these numbers into a vector "data"

This is my code:

int main() {
    ifstream fin("parameters.txt");
    vector<double> data(8);

    int element;
    while (fin >> element) {
        data.push_back(element);
    }
    for (int i = 0; i < 8; i++) {
        cout << data[i];
    }
    cout << endl;
}

However, when I run the code, and try to output data, I get:

00000000

as an output. What is the problem?

question from:https://stackoverflow.com/questions/65941060/reading-numbers-from-a-space-delimited-text-file-in-c

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

1 Reply

0 votes
by (71.8m points)

If you want to reserve elements before inserting them, to make your code more efficient, you can use

vector<double> data;
data.reserve(8);
//push_back as you did

This creates an empty vector and sets the capazity to 8 elements. You can also omit the reserve, than it will be done for you, but not in one step.

Also note that you can replace the last for loop

for (int i = 0; i < 8; i++) {
        cout << data[i];
}

by a range-based for-loop, because the index is not necessary:

for (double i : data) {
  cout << i;
}

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

...