Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c programming scanf

Tags:

c

morse-code

I been given this assignment and this is the code I made so far. This code is only accepting one letter when it should do more than on letter, so I could type in a word and it would be in Morse code

#include "stdafx.h"
#include <ctype.h> 
#include <stdlib.h>
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
  char input[80], str1[100];

  fflush(stdin);
  printf("Enter a phrase to be translated:\n");
  scanf("%c", &input);
  int j = 0;
  for (int i = 0; i <= strlen(input); i++)
    {
      str1[j] = '\0';
      switch(toupper(input[i]))
        {
          ..................
        }
      j++;
    }
  printf("\nMorse is \n %s\n", str1);
  fflush(stdout);
  //printf("%s\n ",morse);
  free(morse);
}
like image 595
halo_4 Avatar asked Nov 16 '25 14:11

halo_4


2 Answers

Your scanf has %c which expects only one character. Use %s to read a c-string:

scanf("%s", input);

Arguments to scanf() are of pointer type. Since a c-string name is the pointer to the first element, there's no need to say address-of (&).

if you were to read only a single character, you need to use &.

E.g.:

scanf("%c", &input[i]); // pass the address of ith location of array input.
like image 111
P.P Avatar answered Nov 19 '25 09:11

P.P


Read a string using %s not %c. Also a character string is already a pointer, no need to get its address. So transform this:

scanf("%c", &input);

into:

scanf("%s", input);
like image 35
Ivaylo Strandjev Avatar answered Nov 19 '25 08:11

Ivaylo Strandjev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!