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

时间:2013-06-30 16:01:23

标签: 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

3 个答案:

答案 0 :(得分:8)

假设您希望将数据存储为浮点数(而非字符串),您可能希望执行以下操作:

#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; in.open("Qi.txt");。同样,最好直接从istream迭代器初始化行向量,而不是创建一个空向量,然后在显式循环中填充它。

最后,请注意,如果你坚持编写一个显式循环,那么你永远想要使用像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>() );

答案 1 :(得分:5)

首先你需要一个矢量:

std::vector<std::string> lines; // requires #include <vector>

然后你需要从getline操作取一个字符串,并将其推回到向量中。这很简单:

for (std::string line; std::getline(myReadFile, line);) 
{
    lines.push_back(line);
}

对于输出操作,您只需要:

{
    int i = 0;

    for (auto a : lines)
    {
        std::cout << "lines[" << i++ << "] = " << a << std::endl;
    }
}

答案 2 :(得分:0)

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
string line;
ifstream myReadFile;
myReadFile.open("Qi.txt");
if(myReadFile.is_open())
{
  for(int i=0;i<7;++i)
    if(myReadFile.good())
    {
        getline(myReadFile,line);
        cout<<"line["<<i<<"] = " << line << endl;
    }
    myReadFile.close();
}
return 0;
}