c++ - 如何使用 C++ 将字符串文件 txt 解析为数组

标签 c++

我正在尝试编写 C++ 程序,但我不熟悉 C++。我有一个 .txt 文件,其中包含如下值:

0
0.0146484
0.0292969
0.0439453
0.0585938
0.0732422
0.0878906

我在我的C++代码中所做的如下:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string line;
    ifstream myReadFile;
    myReadFile.open("Qi.txt");
    if(myReadFile.is_open())
    {
        while(myReadFile.good())
        {
            getline(myReadFile,line);
            cout << line << endl;
        }
        myReadFile.close();
    }
    return 0;
}

我想使程序的输出成为一个数组,即

line[0] = 0
line[1] = 0.0146484
line[2] = 0.0292969
line[3] = 0.0439453
line[4] = 0.0585938
line[5] = 0.0732422
line[6] = 0.0878906

最佳答案

假设您希望将数据存储为 float (而不是字符串),您可能希望执行如下操作:

#include <iostream>
#include <vector>
#include <iterator>
#include <fstream>

int main() { 
    std::ifstream in("Qi.txt");

    // initialize the vector from the values in the file:
    std::vector<double> lines{ std::istream_iterator<double>(in),
                               std::istream_iterator<double>() };

    // Display the values:
    for (int i=0; i<lines.size(); i++)
         std::cout << "lines[" << i << "] = " << lines[i] << '\n';
}

关于样式的简要说明:我更喜欢在创建变量时看到变量已完全初始化,因此 std::ifstream in("Qi.txt"); 优于 std::ifstream 输入; in.open("齐.txt");.同样,最好直接从 istream 迭代器初始化线 vector ,而不是创建一个空 vector ,然后在显式循环中填充它。

最后,请注意,如果您无论如何都坚持要编写一个显式循环,那么您永远都不想使用像while (somestream.good()) 这样的东西while (!somestream.eof()) 来控制你的循环——它们大多是坏的,所以它们不能(可靠地)正确读取文件。根据所涉及的数据类型,他们经常会从文件中读取最后一项两次。通常,您需要像 while (file >> value)while (std::getline(file, somestring)) 这样的东西。这些在读取后立即检查文件的状态,因此一旦读取失败,它们就会退出循环,避免 while (good()) 样式的问题。

哦,作为旁注:这是在期望编译器(至少在某种程度上)符合 C++11 的情况下编写的。对于较旧的编译器,您需要更改此设置:

    // initialize the vector from the values in the file:
    std::vector<double> lines{ std::istream_iterator<double>(in),
                               std::istream_iterator<double>() };

...像这样:

    // initialize the vector from the values in the file:
    std::vector<double> lines(( std::istream_iterator<double>(in)),
                                std::istream_iterator<double>() );

关于c++ - 如何使用 C++ 将字符串文件 txt 解析为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392218/

相关文章:

c++ - Qt和串口编程

C++ 函数在 while(GetMessage(...)){...} 中不起作用

c++ - clang,返回带有类型转换的 std::unique_ptr

C++ 声明独立于平台的 32 位 float

c++ - 比较范围构造函数中的迭代器 value_type

c++ - 在没有 friend 的情况下授予对私有(private)构造函数的访问权限?

c++ - 关于c++中的括号

c++ - 使用 DMA 在我的 nucleo-L432KC 上设置时钟以进行 5 channel adc 转换

c++ - 如何计算以任意字符集编码的字符串中的字符数

C++ 包含守卫