0

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");
}
David G
  • 94,763
  • 41
  • 167
  • 253
Robert
  • 19
  • 2

1 Answers1

2

Try

Replacing

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;
    }
}

with

for(i=0;i<=strlen(s)-1;i++)
{
    if(s[i] == ' ')
    {
        tmp[i] = '\n';
    }
    else
    {
        tmp[i] = s[i];
    }
}
marsh
  • 2,592
  • 5
  • 29
  • 53
  • no no no... I want to copy the string s in tmp, WORD by WORD – Robert Nov 14 '14 at 20:43
  • I am confused, could you try explaining better what exactly you want your tmp variable to contain? I thought you wanted the original string with new lines instead of spaces. – marsh Nov 14 '14 at 20:49
  • Well... I'm trying to separate each word like the strtok function do but in another way...and put them into a new string – Robert Nov 14 '14 at 20:54