c++ - 通用 VC++ 与 g++ 查询

标签 c++ string visual-c++ g++ header

我无法理解编译器。 下面的代码在 UNIX 下的 g++ 下可以工作,但在 VC++ 下它甚至不能编译。任何人都可以提供合理的理由吗?

#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;

}

下面的错误是 VC++ 抛出的,但在 g++ 中它工作正常。

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

g++ 的输出:

Enter the string : BD2d1100mayor47E N/W msg : D2d1100mayor crc chksum : 47

最佳答案

您需要替换 #include <string.h>通过 #include <string>

C++ 头文件没有 .h扩展以将它们与具有相同名称的 C header 区分开来。

此外,您不需要 #include <stdio.h>程序的 header ——如果您需要从 C++ 程序调用 stdio 函数,您应该 #include <cstio>无论如何。


编辑:“如果这确实是问题所在,错误应该出在字符串变量的定义上”,PierreBdR 评论道

在 MSVC++ 中,#include <iostream>创建级联包含,在某些时候#include <stdexcept> .然后当你查看 stdexcept 时头文件,可以看#include <xstring> . std::string的MSVC++定义与实现真的在这个xstring header 解释了为什么编译器知道类型,即使你不知道 #include <string> .

然后如果你看string的内容 header ,您可以看到这是与 std::string 兼容的二元运算符的位置被定义这解释了为什么错误只在包含 cin >> buffer; 的行上弹出声明。

关于c++ - 通用 VC++ 与 g++ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1865629/

相关文章:

c++ - 避免 LAPACK 中的矩阵半矢量化

c++ - 将自定义 GTK+ 小部件编译为 C++

java - 如何优化代码以始终使用对 String 的相同引用而不增加内存使用量?

C# 将具有空值的字节数组转换为字符串

security - 是否可以在不登录的情况下模拟用户?

c++ - Qt networkAccessibleChanged 信号未触发

java - System.in.read() 行为我无法解释

windows - 如何以编程方式更改默认声音播放设备?

c++ - 如何使用CMake仅在一种模式下拥有变量

c++ - 如何检查一个值是否为1.#INF0000?