c++ - 如何使此功能停止在 N 个字符/
问题描述
所以我有这个任务是获取一个文本文件的内容并将其复制到另一个。我们必须重写 strncpy 默认函数,但略有不同。以下是实验室明确写下的内容:
此函数替换 std::strncpy 函数。也就是说,它将 s2 的内容复制到 s1,但不超过 N 个字符。提示:由于 strlength(和 std::strlen)不计算空终止字符,请记住在调用 strncopy(和 std::strncpy)时将该数字加一。为避免产生分段冲突,您必须在取消引用 s2 以将数据复制到 s1 之前检查是否遇到了空终止字符。同样,将您的代码基于指针循环。
这是我到目前为止的功能:
void strncopy(char *s1, const char *s2, int N){
// return if no memory is allocated to the s1
if (s1 == NULL)
NULL;
// take a pointer pointing to the beginning of s1 string
char *ptr = s1;
// copy the C-string pointed by s2 into the array
// pointed by s1
while (*s2 != '\0'){
if (*s1 == N){
break;
}
// *s1 = *s2;
s1++;
s2++;
}
// include the terminating null character
*s1 = '\0';
}
它似乎存在的问题是循环在达到 N 个字符时没有停止。
这是我实现此功能的主要功能的一部分:
int main(int argc, char *argv[]) {
// check for four command line arguments
// if not, print error message and bail out
if (argc != 4){
cerr<<"Error";
return -1;;
}
// declare two streams: file1, file2
fstream file1;
fstream file2;
// declare two char text line arrays
char textline1[256];
char textline2[256];
if (strcompare(argv[1], "-copy") == 0) {
//open file1 for reading
file1.open(argv[2]);
//open file2 for writing
file2.open(argv[3]);
//read text line 1 frome file1
while (file1.getline(textline1, 256)) {
// determine length of textline1
char t1 = strlength(textline1);
// copy textline1 to textline2
strncopy(textline2, textline1, (t1+1));
// write textline2 + newline to file2
file2 << textline2 << '\n';
}
}
这是我要复制的文件中的文本:
船长日志,星历 3192.1。进取号正在前往星团 NGC 321 的途中。目标是与已知存在的文明建立外交关系。我们已向星团的主行星 Eminiar 7 发送了一条消息,告知他们我们的友好意图。我们正在等待答案。
这就是我实际复制的内容:
船长日志,星历 3192.1。进取号正在前往星团 NGC 321 的途中。目标是与已知存在的文明建立外交关系。我们已向星团的主行星 Eminiar 7 发送了一条消息,告知他们我们的友好意图。我们正在等待答案。n answer.cluster, .
有谁知道我的问题是什么?很抱歉,这是一个愚蠢的问题,但是自从课程只在线上进行以来,很难从讲师和助教那里获得帮助。
解决方案
目前你有以下检查长度:
if (*s1 == N){
break;
}
但是,由于s1
其中不包含长度(大概),因此您正在比较 中的字符s1
,N
这可能是错误的(但如果s1
未初始化,则为 UB)。
您可以像这样修改您的while
条件:
while (*s2 != '\0' && N--)
当N
达到 0 时,它的条件为假,因此停止循环。这假设N
一开始就大于或等于零。
另外,要添加,您有
// return if no memory is allocated to the s1
if (s1 == NULL)
NULL;
这不会返回,它实际上什么都不做。您想要执行以下操作:
if ( s1 == NULL )
return;
PS:如果您使用的是 C++11 或更高版本,您可能需要考虑使用nullptr
而不是。NULL
推荐阅读
- cassandra - Cassandra,运行子查询的有效方法是什么
- r - 计算 hclust 树状图中两个节点之间的距离
- visual-studio - 如何通过 Powershell 启动 VS 插件
- r - 这个 R 成语的目的(match.call 后跟 eval(parent.frame())
- php - 无法正确连接字符串中的修剪函数
- reactjs - 无法在 Elastic Beanstalk 上部署节点:命令“/bin/sh -c npm install”返回非零代码:1
- r - 尊重条件时如何在两个数据框之间粘贴值
- php - 将 Firebase 与 php Codeigniter 3 连接的任何解决方案或方法?
- angular - 特定组件上的特定 SCSS 不起作用
- c++ - 为什么具有私有构造函数的类不阻止从此类继承?如何控制哪些类可以从某个基类继承?