【发布时间】: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
每个操作系统上的标头是否不同?
注意:
请停止投反对票:我已经收到消息了。
【问题讨论】:
-
<string>:std::string和朋友们,<cstring>:为字符串事物提供 C API (string.h) -
你在做
new没有delete,你肯定有内存泄漏。 -
避免使用 cstrings。避免原始指针。避免内存分配。使用 stl 容器。您目前正在学习糟糕的编码风格。
-
和
using namespace std也是你不应该养成的习惯。不要那样做。 -
@VansFannel "(对不起,我不知道你怎么称呼可以在Windows、Linux、MacOS等上编译的代码)"它叫可移植代码.