I'm a beginner with C++ and I wish to learn more about characters but I've got a problem. I have tried to make a program which copies a sentence and adds a new line ('\n'
) between spaces (' '
), like separating a sentence word by word.
int main()
{
char s[256], tmp[256];
int m, n = 0, i;
cout << "String: ";
gets(s);
for (i = 0; i <= strlen(s) - 1; i++)
{
if (s[i] == ' ')
{
m = i;
if (n > strlen(s)) tmp[0] = 0;
else
{
if (m >= strlen(s) - n + 1)
for (i = 0; i <= strlen(s) - n + 1; i++)
tmp[i] = s[n - 1 + i];
else
for (i = 0; i < m; i++) tmp[i] = s[n - 1 + i];
}
strcat(tmp, "\n");
n = i;
}
}
cout << tmp;
system("PAUSE");
}