如何在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++
伪码:
#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]
输入字符串。
相关文章:
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 如何在线程中初始化对象,然后在其他地方使用它?
- 使用函数打开文件,然后让其他函数利用该文件?
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- C++挂起线程,然后通过其他线程重新激活
- 在其他编译器中使用_DEBUG定义,然后在Visual Studio中使用
- 如何引用无效的输入,然后重新输入和如果其他语句
- 文件仅读取1个记录,然后到达文件的末尾,即使还有其他记录
- C++ 将文件中的数字读取到数组中,然后将其打印到其他数组中
- c++ 输入一个数字来确定其他数字,然后比较它们
- static_cast到其他类型,然后移动结果
- 在源文件中定义数组,然后在其他源文件中使用它
- 在函数内部创建一个局部向量,然后将其作为引用传递给其他函数,这些函数将其存储为引用
- 从txt文件中读取数字,添加一些数字,然后在c ++中将其重写为其他文件
- 将一个数字的一个数字与其当前位置相乘,然后使用递归将其和其他数字相加
- 将迭代器存储在临时容器上,然后从其他容器中删除它们
- 从一个组合框中选择项目,然后从其他组合框中删除该项目
- 如何在主函数中连接到数据库,然后从其他函数引用它
- 从数组中移除元素,然后将其他元素移到上面
- 在QStringList中搜索特定项目,然后搜索可能包含项目的其他项目