2017-08-14 288 views
0

我在Windows和Linux中运行代码。 在Window中,我可以得到我想要的结果,但在Linux中,我从Window获得了不同的结果。Windows和Linux之间的程序输出不同。为什么?

是什么导致了这种差异,以及如何修复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; 
} 

这在代码声明为“raw_file”输入;

/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的结果; (意外结果)

​​
+2

'while(!infile.fail())'在读取之前检查失败。不要指望这个工作。 – user4581301

+0

最终值似乎包括linux上的换行符(例如''html \ n“'而不是''html'') – Justin

+0

如果输入文件是在Windows上创建的,它将包含窗口行尾:\ r \ ñ。这会在Linux下搞乱你的输出,因为它会打印\ r。 – user4581301

回答

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 

与回车移动光标回到行的开头,t他用最后一个覆盖第一个/

简单的解决方案是将输入文件转换为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之前。

+0

我在Window中编写了代码,这就是造成这种差异的原因。我没有想到Window和Linux之间的不同行结尾(\ r \ n和\ n)。感谢您的明确解释! :) – jjjhseo

相关问题