0

Hey guys Im having trouble printing out a string. Could someone help me out? I would like to enter a string like: "julie perez" and print out "julie perez" but my program only outputs "julie". The code that prints out only "julie" is the following:

practice.c:

#include <stdio.h>
#include "practice.h"
#define TWENTY_FIVE 25

int main () {
  char cara[TWENTY_FIVE];
  
  printf("Enter String> ");
  scanf("%s", cara);
  
  display(cara);
  
  return 0;
}

practice.h (header file):

#ifndef PRAC_H
#define PRAC_H

void display(const char*str);

#endif

practicefuncs.c (function):

#include <stdio.h>
void display(const char *str) {
  
  while (*str != '\0') {
    if (*str == ' ') {
      printf(" ");
    } 
    else {
      printf("%c", *str);
    }
    str++;
  }
  printf("\n");
}

I think my functions are correct because when i declared a string (Ex. cara[] = "julie perez") it displayed "julie perez". I think its the input from user im not getting. Well they way i have it, when it scans the string from the user, is it saying put a '\0' after the first blank?? In this case "julie" so thats why its only printing julie??

Edited by speedy94519: n/a

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by speedy94519
0

scanf's %s specifier stops reading on whitespace. If you want to read a string with embedded whitespace, fgets is the better option. That way you can read a whole line and then continue to parse it if needed.

#include <stdio.h>
#include "practice.h"
#define TWENTY_FIVE 25

int main () {
  char cara[TWENTY_FIVE];
  
  printf("Enter String> ");

  if (fgets(cara, sizeof cara, stdin))
    display(cara);
  
  return 0;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.