简体   繁体   English

从 C++ 中的空格分隔文本文件中读取数字

[英]Reading numbers from a space delimited text file in C++

I'm trying to read a file "parameters.txt" from the working directory.我正在尝试从工作目录中读取文件“parameters.txt”。

This is parameters.txt:这是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:但是,当我运行代码并尝试 output 数据时,我得到:

00000000

as an output.作为 output。 What is the problem?问题是什么?

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.这将创建一个空向量并将容量设置为 8 个元素。 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 循环

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

by a range-based for-loop, because the index is not necessary:通过基于范围的 for 循环,因为索引不是必需的:

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

Your code has 3 bugs:您的代码有 3 个错误:

  1. you creating vector with 8 zero values at start: vector<double> data(8);您在开始时创建具有 8 个零值的向量: vector<double> data(8); , later you are adding new values at the end ,稍后您将在最后添加新值

  2. Your variable element has int type, so fin >> element will read only 1 from text file leaving .0 for further reading.您的变量element具有int类型,因此fin >> element将仅从文本文件中读取1 ,留下.0以供进一步阅读。 During next iteration reading of int will fail since dot is encountered.在下一次迭代期间, int的读取将失败,因为遇到 dot。

  3. You code always prints 8 values from vector (so if file opening failed and problem 1 is fixed you will have undefined behavior).您的代码始终从向量打印 8 个值(因此,如果文件打开失败并且问题1已修复,您将有未定义的行为)。

The solution is:解决方案是:

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

    double element;
    while (fin >> element) {
        data.push_back(element);
    }
    for (size_t i = 0; i < data.size(); i++) {
        cout << data[i] << ", ";
    }
    cout << endl;
}

https://wandbox.org/permlink/1CvTf7YY89C6hUyh https://wandbox.org/permlink/1CvTf7YY89C6hUyh

Which can be simplified to this:可以简化为:

int main()
{
    ifstream f{"parameters.txt"};
    vector<double> v{istream_iterator<double>{f}, {}};
    
    for (auto x : v) {
        cout << x << ", ";
    }
    cout << endl;

    return 0;
}

https://wandbox.org/permlink/Pcxz4gPakXwhzzvl https://wandbox.org/permlink/Pcxz4gPakXwhzzvl

vector<double> data(8);

You defined data as vector of double type with 8 items that they initiated by double default 0.0 !您将数据定义为 double 类型的向量,其中包含 8 个项目,它们由double默认0.0启动! So using push_back will increase vector size and inserts at new index!所以使用push_back会增加向量大小并在新索引处插入! So data[0] to data[7] stills are 0 !所以data[0]data[7]仍然是0

You can try你可以试试

vector<double> data(8);
int index = 0;
while (fin >> element && index < 8)
{
    data[index] = element;
    ++index;
}

Other problem!其他问题! your file contains double values!您的文件包含双值! So how you read them as int!那么你是如何将它们读为 int 的! such int element; fin >> element这样int element; fin >> element int element; fin >> element ? int element; fin >> element

modify code as below to work properly!修改如下代码以正常工作!

double element;
int index = 0;
while (fin >> element && index < 8)
{
    data[index++] = element;
}

The line线

vector<double> data(8);

does not set the initial capacity of the vector, it create a vector with n initial default-constructed elements.不设置向量的初始容量,它创建一个具有n 个初始默认构造元素的向量。 Then you're pushing new values to the end of that vector.然后你将新值推到该向量的末尾。 When you output the first n elements of the vector you are only getting those initial elements.当你 output 向量的前n 个元素时,你只会得到那些初始元素。

And, your input statement is inputting into an int variable which you're then storing into a vector of doubles.而且,您的输入语句正在输入一个int变量,然后您将其存储到一个双精度向量中。

Also your output statement does not add any spaces, so your zeros are all mushed together.此外,您的 output 语句不添加任何空格,因此您的零都混在一起。

change int element to double elementint 元素更改为double 元素

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

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM