我遇到了下面的代碼問題,因爲我似乎無法得到strncpy只輸出命令行參數的前3個字符我已經通過我的程序。另外,我無法將修剪過的字符串打印到 ostream,我將它們傳遞給我的重載操作符。 主和所有模塊的代碼粘貼下面:在使用C++輸出字符串和strncpy時遇到問題
#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]);
}
}
可能值得看格式。此外,你似乎已經重複了一些代碼。 –
在'strcpy'目標是第一個參數。另外,我沒有看到爲「裁剪」分配空間的位置。 (例如:'trimmed = new char [(strlen(original)+ 1]') –
您沒有在代碼中使用'strncpy'。您使用過'strcpy'。問題或代碼中是否有錯字? – user2079303