Windows和Linux之间的程序输出不同。为什么?

时间:2017-08-14 22:01:40

标签: c++ linux simulation

我在Windows和Linux中运行代码。 在Window中,我可以获得我想要的结果,但是在Linux中,我得到的结果与我从Window获得的结果不同。

导致这种差异的原因是什么以及如何在Linux中修复代码?

非常感谢! :)我附加了两个操作系统的代码,输入和结果。

以下是我的代码; (此代码是使用点反向排序组件并使用斜杠区分组件。)

#include <iostream>
#include <fstream>
#include <string>
#include <vector>


using namespace std;

string set_name = "6000k";

// in
string raw_file = set_name + "_filtered.txt";
// out
string set_file = set_name + "_filtered_dot.txt";

// main
int main()
{
    int i = 0;
    string comp = ""; 
    string str; 

    vector<string> input_comp;
    vector<string> tmp_comp; 
    int input_order = 0;

    ifstream infile;
    infile.open(raw_file);

    ofstream outfile;
    outfile.open(set_file);

    if (infile.fail()) // error handling
    {
        cout << "error; raw_file cannot be open..\n";
    }

    while (!infile.fail())
    {
        char c = infile.get();

        if (c == '\n' || c == '/')
        {
            if (comp != "") 
            {
                input_comp.push_back(comp);
            }

            int num = input_comp.size();
            for (int j = 0; j < num; j++)
            {
                int idx = (num - 1) - j;
                outfile << "/" << input_comp[idx];
            }

            if (c == '\n')
            {
                outfile << "/" << endl;
            }

            input_comp.clear();
            str = "";
            comp = "";
        }
        else if (c == '.')
        {
            if (comp != "") 
            {
                input_comp.push_back(comp);
            }

            comp = "";
        }
        else 
        {
            str = c;
            comp = comp + str;
        }

    }

    infile.close();
    outfile.close();

    return 0;
}

这是&#39; raw_file&#39;中的输入。在代码中声明;

/blog.sina.com.cn/mouzhongshao
/blogs.yahoo.co.jp/junkii3/11821140.html
/allplayboys.imgur.com

这是Window的结果; (这是我想从上面的代码中得到的)

/cn/com/sina/blog/mouzhongshao/
/jp/co/yahoo/blogs/junkii3/html/11821140/
/com/imgur/allplayboys/

这是Linux的结果; (意外结果)

/cn/com/sina/blog/mouzhongshao
/
/jp/co/yahoo/blogs/junkii3/html
/11821140/
/com
/imgur/allplayboys/

1 个答案:

答案 0 :(得分:1)

Windows使用复合行尾:回车和换行(\r\n)。当C ++文件流以文本模式打开文件时,默认情况下会找到\r\n,它会以静默方式将其转换为\n

Linux仅使用换行符(\n)。当文件流找到\r\n时,\r被视为常规字符并传递给解析器。

所以在Linux上/blog.sina.com.cn/mouzhongshao\r\n被分解为

<empty>
blog
sina
com
cn
mouzhongshao\r

根据控制台的处理方式\r可能会打印

/cn/com/sina/blog/mouzhongshao
/

/cn/com/sina/blog/mouzhongshao

使用回车将光标移回到行的开头,并用最后一个覆盖第一个/

简单的解决方案是将输入文件转换为Linux样式的行结尾。许多Linux文本编辑器都内置了DOS到Unix格式转换实用程序。还有广泛使用的dos2unix应用程序。如果所有其他方法都失败了,请在Linux下重写该文件。

更长的解决方案是使Windows和Linux的行为相同。这方面的许多例子已经存在。这是一个:Getting std :: ifstream to handle LF, CR, and CRLF?

请注意while (!infile.fail())因为它在阅读前测试可读性,这意味着所有后续阅读都可能失败并且您不会知道。更多相关内容:Why is iostream::eof inside a loop condition considered wrong?

要解决此问题,请不要立即将infile.get();的结果投射到char保持int一段足够长的时间,以便在使用之前查看结果是否为Traits::eof()值为char

相关问题