我有一个像这样的简单 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
完全相同,但第一个正常工作而第二个不正常 为什么这是编译器错误??
最佳答案
这两行不一样——第二行有多字节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 ;.
第二行的一些空格属于 U+2009 'THIN SPACE'
品种(UTF-8 格式的 e2 80 89
)。
编译器不喜欢这些空格并表达了它的不满(我认为这是一个相当明确的错误消息)。
关于C++ 表现出奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26192395/