Я начинающий студент C++ и я столкнулся с проблемой, с помощью следующего кода:строка не заканчивается нулем
Я пытаюсь объединить «новую строку» или "\n"
в строку в матрице of char. До сих пор мне удалось объединить символ " "
, но char "\n"
или просто набрав несколько " "
не будет работать.
Фактический образец получает 3 строки в const значение 10 (максимальные символы) для каждого из 3 определяемых пользователем значений матрицы 3 для первых двух и использование функции для «изменения» третьей и ее печати.
#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_s (text3 [i]," \ n "// not working' является очевидной синтаксической ошибкой, которая, судя по остальной части вашего кода, вы, вероятно, действительно не использовали. – hvd
Просто используйте' std :: string'. На самом деле, все будет проще и лучше. –
извините меня, но я не понимаю, это реальный код, который я пробовал. И то, что я пытаюсь понять здесь, - что я должен положить вместо символа «\ n». Stokes - какова функция/метод, о котором вы упомянули, havent узнал об этом еще ...:/ –