0
#include <stdio.h>
#include <conio.h>

#define MAX 25
char welcomeMsg[]="Please enter your name without * or #";
char errorMsg[]="Error, please try again";
void main(void)
{
    int j;
    char name[MAX],input;
    j=0;
    printf("%s\n", welcomeMsg);

do
{
gets_s(name,24);
if(name[j]=='#'|| name[j]=='*')
{
    printf("%s\n", errorMsg);
    j=0;
    continue;
}
name[j]=name[j]+j;

j++;

}while(name[j]<25&&name[j]!='\n');

name[j]=0;NULL;

puts("\nYour Name is");
printf("%s",name);
}

not sure when programs runs, only 1st chracter of string is displayed :( It's my first time doing strings and I'm quite new to c++ so i desperately need help on what is actually wrong. Why isn't my string displaying as a whole? Only 1 character displayed.

  • 1
    If you stare at this for a while (pun intended): `while(name[j]<25&&name[j]!='\n')`, it should only take you a few minutes to figure out the answer. If not, now is a great opportunity for you to learn how to use a debugger. – Sam Varshavchik Jan 10 '17 at 11:53
  • 8
    If this is C++, then you should **immediately abandon** the reference material you are using to learn, and switch to [a better one](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) ASAP. – WhiZTiM Jan 10 '17 at 11:54

1 Answers1

4

The problem is this expression in your loop condition: name[j]<25.

In the first iteration you will compare name[1] against 25. Assuming the ASCII alphabet, unless that character is a control character then the loop will end and you will set the terminator at name[1].

The condition you probably want is j < 25. You should probably add a check for the string terminator as well.

This would have been very obvious if you just used a debugger and stepped through the code. Next time please do that first.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621