gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:46:32 24 4
gpt4 key购买 nike

我无法理解编译器。下面的代码在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com