如何在c++中读取以空格分隔的数据并将其保存到数组中,然后以其他顺序写入新的文本文件

how to read data delimited by space and save it to arrays,and then write it other order in new text file in c++

本文关键字:其他 然后 数组 文件 顺序 文本 读取 c++ 空格 分隔 数据      更新时间:2023-10-16

伪码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
    string line;
    double beta[250];
    char Batob[250], eq[250];
    ifstream myfile("iter1/HMMemit0.txt");
    if (myfile.is_open())
    {
        int i = 0;
        while (getline(myfile, line))
        {
            istringstream iss(line);
            if (!(iss >> Batob[i] >> eq[i] >> beta[i])){ //it store only B in Batob[i], but i want to save B00 in Batob[i], = in eq[i], and 0.524671 in beta[250]
                break;
            }
                i++;
        }
        myfile.close();
    }
    else cout << "Unable to open file";
    return 0;
}

我的数据像这样存储在HMMemint0中

B00 = 0.524671 
B01 = 0.001000 
B02 = 0.001000 
B10 = 0.001097 
B11 = 0.001000 
B12 = 0.001000 

我想读取一行并将每个术语保存在每个变量中,例如B00保存在name[i]中,而0.001000保存在beta[i]中。然后,按照0.524671(B00的值)0.001097(B10的值)的顺序写,像这样

0.524671 0.001097  
0.001000 0.001000 
0.001000 0.001000 

我该怎么做呢?

你有一个字符数组的"BXX"s,而你想要字符串。基本上,你想要一个字符串数组,甚至是向量。问题是只有'B'会从"BXX"中读取到你的第一个参数中。

这段代码为我工作:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
    string line;
    double beta[250];
    string Batob[250];
    char eq[250];
    ifstream myfile("iter1/HMMemit0.txt");
    if (myfile.is_open())
    {
        int i = 0;
        while (getline(myfile, line))
        {
            istringstream iss(line);
            iss >> Batob[i] >> eq[i] >> beta[i];
            i++;
        }
        myfile.close();
    }
    else cout << "Unable to open file";
    return 0;
}

免责声明:我只是在以最小的影响修复你的代码,但当然,如果你开始使用适当的c++容器,如vector, i变量可以很容易地消除,因为元素和索引将被自动维护。

此外,由于您一直对字符数组使用等号('='),这有点不必要的内存浪费,在大文件的情况下可能会很严重。

我想说的是,将来使用关联容器对于您的BXX键和右侧相应的values键将更加高效。

Batob是字符数组,因此Batob[i]是单个字符。这就是为什么您的程序只读取一个字符。如果您想要读取250 字符串,则需要为它们腾出空间。最简单的(但不一定是最好的)方法是声明一个像char Batob[250][100]这样的数组——这将是一个包含250个数组的数组,每个数组有100个字符。然后Batob[i]是一个100个字符的数组,您可以使用iss >> Batob[i]输入字符串。

相关文章: