生成空输出文件

问题描述 投票:0回答:1

我用 C++ 编写了一段代码,用于在我的系统中生成输出文件。该函数正在执行,但唯一的问题是生成的输出文件是空的。谁能告诉我我做错了什么?

输入文件是这样的:

"1","02","Advance notification (confirmed)","Use for a complete record issued to confirm advance information approximately six months before publication; or for a complete record issued after that date and before information has been confirmed from the book-in-hand","0"

我写的代码:

#include <fstream>
#include <sstream>
#include <iostream>

int main() {
    std::ifstream inputFile("/Users/a0p0ieu/Desktop/specRules/list.csv");
    std::ofstream outputFile("/Users/a0p0ieu/Desktop/specRules/output_spec.txt");
    std::string line;

    while (getline(inputFile, line)) {
        std::istringstream iss(line);
        std::string col1, col2, col3;
        getline(iss, col1, ',');
        getline(iss, col2, ',');
        getline(iss, col3, ',');

        if (col1 == "1") {

            outputFile << "\"" << col2 << "\": {\n";
            outputFile << "    \"#" << col3 << "\": \"onix_productformcode.values[].value\"\n";
            outputFile << "},\n";
        }
    }

    inputFile.close();
    outputFile.close();
    return 0;
}

输出应该是这样的:

 {
    "2": {
      "#Advance notification (confirmed)": "onix_notificationtype.values[].value"
    }
  }

相同的代码正在我朋友的笔记本电脑上运行。

c++ file debugging output
1个回答
0
投票

您的代码中有 2 个问题,都与用引号引起来的值相关

    输入文件中的
  1. col1
    包含
    "1"
    (即文本包含引号),而不是
    1
    ,因此当您比较此行中的值时:
    if (col1 == "1") {
    
    应改为:
    if (col1 == "\"1\"") {  // note the escaped quotes in the strings content
    
  2. 类似地,输入文件中的
  3. col2
    col3
     也包含带引号的值,因此当您将其写入输出文件时,您实际上应该 
    not 添加额外的引号。因此这些行: outputFile << "\"" << col2 << "\": {\n"; outputFile << " \"#" << col3 << "\": \"onix_productformcode.values[].value\"\n";
    应改为:
    
    outputFile << col2 << ": {\n"; outputFile << " #" << col3 << ": \"onix_productformcode.values[].value\"\n";
    
    
通过这 2 个修改,输出文件将包含您期望的内容:

"02": { #"Advance notification (confirmed)": "onix_productformcode.values[].value" },
    
© www.soinside.com 2019 - 2024. All rights reserved.