I have trouble understanding the compilers. The following code does work in UNIX under g++, but under VC++ it would not even compile. Anyone can provide valid reasons why?
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string tmp_nw_msg, crc_chksum, buffer;
cout << "Enter the string : ";
cin >> buffer;
if (strlen(buffer.c_str()) >15 ) {
tmp_nw_msg = buffer.substr(1,12);
crc_chksum = buffer.substr(13,2);
cout << " N/W msg : "<< tmp_nw_msg << endl;
cout << " crc chksum : "<< crc_chksum << endl;
}
else {
cout << "error" << endl;
}
std::cin.get();
return 0;
}
The following error is th开发者_如何转开发rown by VC++, but in g++ it does work fine.
Error 1 error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) c:\documents and settings\my documents\visual studio 2005\projects\dummy_substr\dummy_substr\substr.cpp 13
Error 2 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) c:\documents and settings\my documents\visual studio 2005\projects\dummy_substr\dummy_substr\substr.cpp 19 Error 3 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) c:\documents and settings\my documents\visual studio 2005\projects\dummy_substr\dummy_substr\substr.cpp 20 Error 4 fatal error C1075: end of file found before the left brace '{' at 'c:\documents and settings\my documents\visual studio 2005\projects\dummy_substr\dummy_substr\substr.cpp(9)' was matched c:\documents and settings\my documents\visual studio 2005\projects\dummy_substr\dummy_substr\substr.cpp 29
Output from g++ :
Enter the string : BD2d1100mayor47E N/W msg : D2d1100mayor crc chksum : 47
You need to replace #include <string.h>
by #include <string>
C++ headers don't have the .h
extension to differentiate them from C headers that would have the same name.
Also, you don't need the #include <stdio.h>
header for your program -- and in case you need to call stdio functions from a C++ program you should #include <cstio>
anyway.
EDIT: "If that really was the problem, the error should be on the definition of the string variables" commented by PierreBdR
In MSVC++, #include <iostream>
creates a cascade of includes which at some point #include <stdexcept>
. Then when you look at the stdexcept
header file, you can see #include <xstring>
. MSVC++ definition and implementation of std::string
really is in this xstring
header which explains why the compiler knows the type even-though you didn't #include <string>
.
Then if you look at the content of the string
header, you can see this is where binary operators compatible with std::string
are defined which explains why the error only pops up on the line containing cin >> buffer;
statement.
精彩评论