【问题标题】:C++ Pipe delimited text file to comma delimitedC ++管道分隔的文本文件以逗号分隔
【发布时间】:2020-04-11 03:55:55
【问题描述】:

如何将管道分隔的文本文件转换为逗号分隔的文件?管道文本文件需要转换为逗号分隔并存储在输出文件中。

例如,如果我有一个这样的管道 .txt 文件:

Available tickets|Seat numbers|Ticket Prices|Total Balance|Tax increase|Payment Method|Ticket Fees|Seats        
1234567|5778|Jonas, Jack|1652|5,873.90|Balance|230|3,567.98|Free soda refills       
1876543|2468|Johnson,George|9059|2,187.53|deposit|904|2,457.90|Price for street parking               
130240|3490|Angel, Mike|4237|1,045.50|Balance|560|3,509.87| Ending Balance

【问题讨论】:

  • 读取输入文件,写入输出文件,一个字符一个字符,将管道转换为逗号字符,是不是太明显了?
  • 这并不容易,因为文件已经有逗号,所以它变得复杂,因为我认为在某些区域也需要添加引号@Sam Varshavchik
  • 好的,那么添加引号。逻辑仍然相当简单,并且仍然可以逐个字符地完成。或者,如果您愿意,std::getline 每行,一次一行,将包含单行的 std::string 拆分为“|”字符,然后输出每个字段,包括引号和“@987654325 @" 作为分隔符。任务完成,是不是很容易?

标签: c++ xcode


【解决方案1】:

为了只在需要的地方添加引号,您可以将管道之间的每个部分存储在一个临时字符串中。

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream input;
    input.open("theFile");

    ofstream output;
    input.open("otherFile");

    string temp;
    while (getline(input, temp, '|')) {
        if (temp.find(",") != string::npos)
            output << '"' << temp << "\",";
        else
            output << temp << ',';
    }
}

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 2016-09-05
    • 2019-05-21
    • 2020-02-02
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多