2014-10-04 50 views
1

我有这样一个简单的C++代码:C++展示奇怪的行为

#include <iostream> 
#include <string> 
using namespace std; 
int main() { 
    int n , a , b ; 
    cin >> n >> a >> b ; 
    //This two lines are exactly same!!!! 
    cout << n - max(a + 1, n - b) + 1 << endl ; 
    //cout << n - max(a + 1, n - b) + 1 << endl ; 
} 

在这段代码中,我有两个线是完全一样的,但是当我编译确切上面的代码,我得到我的结果与任何输入例如(5,2,3),但是当我取消对第二cout和评论的第一个与所有以前的状态代码不编译(GNU 4.8.2),并得到这个错误:

sample.cpp:8:5: error: stray ‘\342’ in program 
    cout << n - max(a + 1, n - b) + 1 << endl ; 
    ^
sample.cpp:8:5: error: stray ‘\200’ in program 
sample.cpp:8:5: error: stray ‘\211’ in program 
sample.cpp:8:5: error: stray ‘\342’ in program 
sample.cpp:8:5: error: stray ‘\200’ in program 
sample.cpp:8:5: error: stray ‘\211’ in program 
sample.cpp:8:5: error: stray ‘\342’ in program 
sample.cpp:8:5: error: stray ‘\200’ in program 
sample.cpp:8:5: error: stray ‘\211’ in program 
sample.cpp:8:5: error: stray ‘\342’ in program 
sample.cpp:8:5: error: stray ‘\200’ in program 

我尝试与Microsoft Visual C++ 2010编译器,我得到了相同的结果,但不同的错误:

program.cpp 
program.cpp(9) : error C2065: 'n¢?%' : undeclared identifier 
program.cpp(9) : error C2065: 'a¢?%' : undeclared identifier 
program.cpp(9) : error C2065: '¢?%1' : undeclared identifier 
program.cpp(9) : error C2065: '¢?%n¢?%' : undeclared identifier 
program.cpp(9) : error C2065: '¢?%b' : undeclared identifier 
program.cpp(9) : error C2146: syntax error : missing ';' before identifier '¢?%' 
program.cpp(9) : error C3861: '¢?%max': identifier not found 
program.cpp(9) : error C2065: '¢?%' : undeclared identifier 
program.cpp(9) : error C2065: '¢?%1' : undeclared identifier 

我无法理解这两个cout是完全一样的,但第一个正常工作和第二个不为什么这是一个编译器错误?

+0

考虑使用不会插入怪异字符不同的文本编辑器。我衷心建议VIM – 2014-10-04 12:13:07

回答

8

这两条线是不一样的 - 第二多字节字符UTF-8在它:

$ cat line1 | xxd -g 1 
0000000: 20 20 20 20 63 6f 75 74 20 3c 3c 20 6e 20 2d 20  cout << n - 
0000010: 6d 61 78 28 61 20 2b 20 31 2c 20 6e 20 2d 20 62 max(a + 1, n - b 
0000020: 29 20 2b 20 31 20 3c 3c 20 65 6e 64 6c 20 3b 20 ) + 1 << endl ; 
0000030: 0a            . 

$ cat line2 | xxd -g 1 
0000000: 20 20 20 20 63 6f 75 74 20 3c 3c 20 6e e2 80 89  cout << n... 
0000010: 2d e2 80 89 6d 61 78 28 61 e2 80 89 2b e2 80 89 -...max(a...+... 
0000020: 31 2c e2 80 89 6e e2 80 89 2d e2 80 89 62 29 e2 1,...n...-...b). 
0000030: 80 89 2b e2 80 89 31 20 3c 3c 20 65 6e 64 6c 20 ..+...1 << endl 
0000040: 3b 0a           ;. 

一些在第二行上的空格的(以UTF-8 e2 80 89)是的U+2009 'THIN SPACE'品种。

编译器不喜欢这些空格,并使其不愉快的已知(我认为是一个相当明确的错误信息)。

+0

我怎么能明白,第一次看,为什么发生这种情况? – 2014-10-04 11:36:22

+0

@ Daniel.V:'xxd'是适用于这种情况的便捷工具。 – NPE 2014-10-04 11:37:58

+0

无论如何,这个错误信息显而易见。它在两种情况下都抱怨应该不在那里的字节。 – Deduplicator 2014-10-04 11:39:06

0

的choise编码例如在记事本++像UTF-8无BOM,我认为这将是确定