【问题标题】:strcpy compiles on Windows but it doesn't on Linux [closed]strcpy 在 Windows 上编译,但在 Linux 上没有 [关闭]
【发布时间】:2019-11-04 11:18:28
【问题描述】:

我正在学习C++并尝试编写通用代码(对不起,我不知道您如何称呼可以在Windows、Linux、MacOS等上编译的代码)。

我已经写了函数trimLeft:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const string rows = "rows:";
const string columns = "cols:";
const string data = "data:";

struct dimensions {
    int rows;
    int columns;
};

inline bool exists (const string& name) {
    ifstream f(name.c_str());
    return f.good();
}

string trimLeft(const string& input) {

    if ((input.empty()) || 
        ((input.at(0) != ' ') && (input.at(0) != '\t')))
        return input;
    else {
        char * tab2 = new char[input.length() + 1];
        char *trimmed = new char[input.length() + 1];

        strcpy(tab2, input.c_str());

        bool skip = true;
        int pos = 0;

        for (unsigned int i = 0; i < (input.length() + 1); i++) {
            if (skip) {
                if ((tab2[i] == ' ') || (tab2[i] == '\t'))
                    continue;
                else {
                    skip = false;

                    trimmed[pos] = tab2[i];
                    pos++;
                }
            }
            else {
                trimmed[pos] = tab2[i];

                if (tab2[i] == '\0')
                    break;
                else
                    pos++;
            }
        }

        string stringTrimmed(trimmed);

        return stringTrimmed;
    }
}

它在显示此警告的 Windows 上编译

警告 C4996:“strcpy”:此函数或变量可能不安全。 考虑改用 strcpy_s。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。

但在 Linux 中,使用以下命令:

g++ FormatMatrix.cpp -o 格式

我明白了:

error: ‘strcpy’ was not declared in this scope

每个操作系统上的标头是否不同?

注意
请停止投反对票:我已经收到消息了。

【问题讨论】:

  • &lt;string&gt;: std::string 和朋友们,&lt;cstring&gt;:为字符串事物提供 C API (string.h)
  • 你在做new 没有delete,你肯定有内存泄漏。
  • 避免使用 cstrings。避免原始指针。避免内存分配。使用 stl 容器。您目前正在学习糟糕的编码风格。
  • using namespace std 也是你不应该养成的习惯。不要那样做。
  • @VansFannel "(对不起,我不知道你怎么称呼可以在Windows、Linux、MacOS等上编译的代码)"它叫可移植代码.

标签: c++ strcpy


【解决方案1】:

作为特定编译器的实现细节,&lt;cstring&gt; 完全有可能被您包含的另一个标头包含(可能在包含树的更远的位置)包含strcpy 的声明。

为确保您的代码真正可移植且符合标准,请包含您调用的每个类和函数的头文件;永远不要想当然地通过包含不同的东西来获得另一个标题的功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2010-11-12
    • 1970-01-01
    相关资源
    最近更新 更多