使用输入和输出文件Sstream

sstream using input and output file

本文关键字:文件 Sstream 输出 输入      更新时间:2023-10-16

所以我有一个文件data3.txt,基本上看起来像这样:

#file:data.txt
#data inputs
1 1234 +0.2 23.89 6.21
2 132 -0.03 3.22 0.1
3    32 0.00 31.50   4.76

,我想使用StringTreams

将前3列写入新文件中
#include <cctype>
#include <sstream>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
  string line;
  float curr_price, change;
  int stock_number;
  ifstream fin("data3.txt");
  istringstream iss;
  ostringstream oss;
  if(!fin){
    cerr<<"Can't open a file";
  }
  ofstream outfile("data2.txt");
  while (getline(fin,line)){
    iss.clear();
    iss.str(line);
    iss>>stock_number>>curr_price>>change;
    while(isspace(iss.peek()))
      iss.ignore();
    while(iss.str() == "#")
      iss.ignore();
    if( iss.str()==""){
      break;
    }
    oss<<stock_number<<"t"<<curr_price<<"t"<<change<<"n";
    outfile<<oss.str();
  }
}

但是我的输出文件看起来很讨厌:

0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
1   1234    0.2
0   0   0
0   0   0
1   1234    0.2
2   132 -0.03
0   0   0
0   0   0
1   1234    0.2
2   132 -0.03
3   32  0

我不知道零来自何处,如果我将Ofstream放在时循环中,那么它将仅打印最后一个数据行

一个问题是,即使您收到评论,您也总是输出数字。另外,不需要窥视和忽略的东西。要检查数字是否已成功读取,请像我在此示例中一样,将流作为布尔值评估为布尔值:

#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char ** argv)
{
    ifstream in(argv[1]);
    ofstream out(argv[2]);
    string line;
    while(getline(in,line))
    {
        if(line.empty() || line[0] == '#') continue;
        double number, price, change;
        stringstream ss(line);
        if(ss >> number >> price >> change)
            out << number << "t" << price << "t" << change << "n";
    }
    return 0;
}
顺便说一句,

这是一个示例的示例,即使用某些C功能会使事情变得更简单又漂亮:

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char ** argv)
{
    string line;
    int number;
    double price, change;
    while(getline(cin,line))
        if(sscanf(line.c_str(), "%d %lf %lf", &number, &price, &change)==3)
            printf("%3d %8.2f %8.2fn", number, price, change);
    return 0;
}

此示例使用标准输入和输出代替文件。这些被称为"标准"是有原因的:它们非常灵活,并且可以非常简单地从文件和其他过程中重定向。但是该程序与文件非常相似。

您需要始终检查您的输入是否成功!另外,您很少需要求助于奇怪的基于角色的阅读技术。例如,有一个操纵器可以跳过领先的空格:std::ws。以下是一个版本,对值的类型没有太大的假设。如果一条线上的第一个值必须是整数,则可以使用int而不是std::string,甚至可以跳过注释行的支票!您只需检查读取三个值是成功的。

#include <sstream>
#include <fstream>
#include <string>
int main()
{
    std::ifstream      in("input.txt");
    std::ofstream      out("output.txt");
    std::istringstream lin;
    std::string        tmp0, tmp1, tmp2;
    for (std::string line; std::getline(in, line); ) {
        lin.clear();
        lin.str(line);
        if ((lin >> std::ws).peek() != '#'
            && lin >> tmp0 >> tmp1 >> tmp2) {
            out << tmp0 << 't' << tmp1 << 't' << tmp2 << 'n';
        }
    }
}