我对下面的代码有问题,因为我似乎无法只输出我通过程序的命令行参数的前 3 个字符。此外,我无法将修剪后的字符串打印到ostream 我为我的超载运算符传递它们。主模块和所有模块的代码粘贴如下:
#include "Cstring.h"
#include <cstring>
#include <iostream>
using namespace w1;
int w1::characters = 3;
Cstring::Cstring(char* orginal) {
if (orginal == nullptr)
trimmed = nullptr;
//strcpy(orginal,trimmed);
cout << orginal << trimmed;
strcpy(orginal,trimmed);
}
ostream& Cstring::display(ostream& output) {
output << trimmed;
return output;
}
ostream& w1::operator<<(ostream& console,Cstring& input) {
static int arguments = 0;
arguments++;
return console << arguments << input.display(console) << "n";
}
#ifndef CSTRING_H
#define CSTRING_H
#include <ostream>
using namespace std;
namespace w1 {
extern int characters;
class Cstring {
const int max = 3;
char *trimmed;
public:
Cstring(char* orignal);
ostream& display(ostream& output);
};
ostream& operator<<(ostream& console,Cstring& input);
}
#endif
#include "Cstring.h"
using namespace std;
using namespace w1;
void process(char* user_data);
#include "Cstring.h"
#include <iostream>
using namespace std;
using namespace w1;
void process(char* user_data) {
Cstring trimmed(user_data);
cout << trimmed
}
#include "process.h"
#include "Cstring.h"
#include <iostream>
#include <cstring>
using namespace std;
using namespace w1;
int main(int argc, char* argv[]) {
if (argc == 1 )
cout << argv[0] << " Insuffienct number of arguments(min 1)" << endl;
cout << "Maximum number of characters stored " << w1::characters << endl;
for (int x = 1 ; x < argc; x++ ) {
process(argv[x]);
}
}
你的程序有点乱。您似乎想做的只是输出每个命令行参数的前 3 个字符,并且您想知道如何使用 strncpy,所以这里有一个最小的示例来说明这一点:
#include <cstring>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i)
{
char buffer[4] = { 0 };
strncpy(buffer, argv[i], 3);
cout << buffer << endl;
}
}
这使用 strncpy 将每个命令行参数的前 3 个字符复制到缓冲区中(大小为 4,因为还需要一个 null 终止符(,然后打印缓冲区的内容。仅复制前 3 个字符。您必须自己处理空终止符。
1(你从不初始化Cstring::trimmed
,除非你把它分配给nullptr
如果original
也是nullptr
。当你试图从nullptr
或单位化trimmed
复制它时,你会得到未定义的行为strcpy(orginal,trimmed);
。
2(您可能不打算从Cstring::trimmed
复制到original
这是argv[x]
,而是打算从original
复制到Cstring::trimmed
。但在这种情况下,您仍然会有未定义的行为,因为您尚未分配任何内存或初始化Cstring::trimmed
(请参阅 1(。
3(您将w1::characters
和Cstring::max
定义为3,但从不使用其中任何一个(除非在main
中输出w1::characters
(。我假设您打算使用其中之一将输出限制为 3 个字符。