【问题标题】: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++ 中的新文本文件中以其他顺序写入
【发布时间】:2014-06-20 16:56:23
【问题描述】:

伪代码:

#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 

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

0.524671 0.001097  
0.001000 0.001000 
0.001000 0.001000 

我该怎么做?请帮帮我。

【问题讨论】:

  • B00s 的 char[] 是一个字符串列表。
  • 由于Batobeq 都是字符数组,因此您的读数会将'B' 读入Batob[i],并将第一个数字读入eq[i]。它们都需要是字符串。
  • 另外,您可能想了解std::map,它是键值对的数据结构,您在输入文件中似乎也有这种结构。

标签: c++ arrays csv


【解决方案1】:

你有一个“BXX”的字符数组,而你想要字符串。基本上,您需要一个字符串数组,甚至是向量。问题是只有“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;
}

免责声明:我只是在以最小的影响修复您的代码,但当然,如果您开始使用像 vector 这样的适当 C++ 容器,则可以轻松消除 i 变量,因为元素和索引将自动维护.

此外,由于您一直对 char 数组使用等号 ('='),因此有点不必要地浪费内存,如果文件很大,这可能会很严重。

我想说,将来使用关联容器对于您的BXX 键和右侧对应的values 会更有效率。

【讨论】:

    【解决方案2】:

    Batob 是一个字符数组,所以Batob[i] 是单个字符。这就是为什么您的程序只读取一个字符的原因。如果您想阅读 250 个字符串,您需要为它们腾出空间。最简单(但不一定是最好的)方法是声明一个像char Batob[250][100] 这样的数组——这将是一个由 250 个数组组成的数组,每个数组 100 个字符。那么Batob[i]是一个100个字符的数组,你可以用iss &gt;&gt; Batob[i]输入一个字符串。

    【讨论】:

    • string 看起来比两个硬编码数组大小的二维数组更适合我。这使得代码很难编码,尽管在这种特殊情况下,可以根据输入假设大小为 3,所以即使这样,100 也可能是过度杀伤力。 :)
    猜你喜欢
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多