c++ - 字符串不以 null 结尾

标签 c++ string function concatenation

我是 C++ 的初级学生,我遇到了以下代码的问题:

我正在尝试将“换行符”或 "\n" 连接到 char 矩阵中的字符串。 到目前为止,我设法连接了一个 "" 字符,但是字符 "\n" 或只是键入多个 "" 将不起作用。

实际示例是为我定义的 3 个矩阵中的每一个获取 3 个常量值为 10(最大字符)的字符串 - 将值分配给前两个并使用函数“更改”第三个并打印它。

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

const int LINES = 3;
const int MAXCHARS = 10; //TO DO: change to 81 for final version

void cpyAndCat(char[][MAXCHARS], char[][MAXCHARS], char[][MAXCHARS], int);
void main()
{
    char text1[LINES][MAXCHARS], text2[LINES][MAXCHARS], text3[LINES][MAXCHARS];

    cout << "Enter " << LINES << " lines into text1:\n";
    for (int i = 0; i < LINES; i++) // assign the matrix of chars text1 with strings
    {
        _flushall();
        cin.getline(text1[i], MAXCHARS);
    }
    cout << "Enter " << LINES << " lines into text2: \n";
    for (int i = 0; i < LINES; i++) // assign the matrix of chars text2 with strings
    {
        _flushall();
        cin.getline(text2[i], MAXCHARS);
    }
    //TO DO: call the function which will recieve text1 and text2 
    //and put blank line(line too long) or copied line from text1 and catanted line form text2.(long correct size)
    cpyAndCat(text1, text2, text3, LINES);
    cout << "============================================================\n";
    for (int i = 0; i < LINES; i++) // print third matrix of chars, prints 3 lines of either text or '\n'
    {
        _flushall();
        cout << text3[i];
        cout << endl;
    }

    system("pause");

}
void cpyAndCat(char text1[][MAXCHARS], char text2[][MAXCHARS], char text3[][MAXCHARS], int lines)
{

    for (int i = 0; i < lines; i++) // searches if length of string from first 2 matrix is valid
    {
        if (strlen(text1[i]) + strlen(text2[i]) < MAXCHARS) // if so, copy the first to the third and catanate the second to the third
        {
            strcpy_s(text3[i], text1[i]);
            strcat_s(text3[i], text2[i]);
        }
        else // if else (: , catanate 'new line' to the third matrix
        {
            strcat_s(text3[i], "\n"); // not working                                                                           
        }
        cout << endl;
    }
}

最佳答案

strcat_sstrcpy_s 需要three parameters, not two .我很惊讶你有任何编译。

另外,你strcattext3 而没有初始化它。所以这可能是未定义的行为......

关于c++ - 字符串不以 null 结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337134/

相关文章:

c# - 在 .NET 中使用字符串格式 "M"发出 DateTime.ToString

c# - 在 C# 中只允许输入数字而不是 NumericUpDown 的文本框

c++ - 为什么我们不能从具有默认参数的函数中调用函数?

c++ - 函数的参数顺序

c++ - 一行调试宏

c++ - Qt 有资源系统限制吗?

python - 使用 Python 2.7 解析文本

c - 从c中的末尾获取链表中的节点值

c++ - ATL C++ 内存泄漏与 ccomobjects safearray

c++ - 单一生产者、单一消费者环形缓冲区的最小限制内存排序?