Replacing ' ' with Enter in Strings

  • Thread starter Thread starter ccky
  • Start date Start date
  • Tags Tags
    Strings
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
ccky
Messages
15
Reaction score
0
The lab requires me to displace that:
Enter a string:This is a string

One word per line is:
This
is
a
string

How can I replace the ' 'with Enter.

Code:
#include <stdio.h>
#define STRSIZE 81

void dispStr(char message[STRSIZE])
{
	int i;
	
	printf("\nOne word per line is :\n");
	 
 
   while (message[i]!=' ')
   {
   	 	
   }
   
}

int main()
{
	char message[STRSIZE];
	
	printf("Enter a string: ");
	gets(message);
	dispStr(message);
	
	return 0;
}

Thanks.
 
Physics news on Phys.org
ccky said:
The lab requires me to displace that:
Enter a string:This is a string

One word per line is:
This
is
a
string

How can I replace the ' 'with Enter.

Code:
#include <stdio.h>
#define STRSIZE 81

void dispStr(char message[STRSIZE])
{
    int i;
	
    printf("\nOne word per line is :\n");
	 
 
    while (message[i]!=' ')
    {
   	 	
    }
   
}

int main()
{
    char message[STRSIZE];
    printf("Enter a string: ");
    gets(message);
    dispStr(message);
	
    return 0;
}

Thanks.

There are a couple problems with the code in your dispStr function.
1. Your loop variable is declared, but no initialized. This will probably cause your loop to try to access memory that doesn't belong to the string. Your loop control variable (i) should be initialized to 0.
2. You don't show any code that increments the loop variable.

To answer your question, when the loop encounters a space character, it should print a newline character ('\n'). You also need logic in our loop so that it prints all of the characters that precede the space before it prints the newline character.
 
  • Like
Likes   Reactions: 1 person