Hi Everyone!!

I have a little problem in printing Character Arrays....
i have enclosed my code below. what problem actually i have is that when i type my first name and after first name (space bar) last name..
it prints only my first name. i want to type whole name after pressing space bar .
and do tell me what i am doing wrong??

thanks in Advance.

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char name[50]; int i,j;
printf("Enter Name : ");
scanf("%s",name[i]);
for (j=name[i]; j<=name[i]; j++)
	{
	printf("\n%s",name[i]);
	}
getch();
}

Recommended Answers

All 6 Replies

scanf() only reads up to the first whitespace (Space, Tab, Return). You want to read the entire line. Use fgets() In general, you don't want to use scanf() to read strings anyway. Here's why.

Plus, think about your loop again. Do you really want the name entered to be your loop index?

Thanks Walt!!

will you please give me some example where i can use fgets();

and you asked me about the index value in for loop:
i use "j=name;" the reason is if you give "j=0; then it will print whatever i scanf as you say will print from 0 to name (40 times or 50 time) i the the limit of my character array.

thanks again

Thanks Walt!!

will you please give me some example where i can use fgets();

the link show how to use fgets() . Where you use it is obvious.

and you asked me about the index value in for loop:
i use "j=name;" the reason is if you give "j=0; then it will print whatever i scanf as you say will print from 0 to name (40 times or 50 time) i the the limit of my character array.

thanks again

I guess my questions are:
1) Why do you need a loop? What's it supposed to be doing?
2) You are looping from nameto name (whatever value i is) which is the same value. And you never initialized i, so it could be 23563 for all you know.

Member Avatar for HASHMI007
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char name[50]; int i,j;
printf("Enter Name : ");
scanf("%s",name);

	printf("\n%s",name);
getch();
}
commented: Still posting bad code with no formatting? Maybe you need to learn how to code before attempting to post code. -4
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char name[50]; int i,j;
printf("Enter Name : ");
scanf("%s",name);

	printf("\n%s",name);
getch();
}

And the point of this post is what exactly? You completely failed to answer the question, or solve the stated problem, and you didn't fix any of the other problems in the code. Because I'm such a nice person, and because you (HASHMI007) could probably use it yourself, I'll list all of the issues and explain how they're fixed. You're welcome.

#include<conio.h>

While conio.h is a useful library, the majority of people who use it don't use it correctly. I'd blame bad compiler examples and crappy books from the 90's, but placing blame is pointless at this point in time. The two biggest misuses of the non-standard conio library are:

  1. Using getch() to pause the program before termination.
  2. Using clrscr() to clear the screen on program startup.

The problem with #1 is that there's a standard solution to the problem of pausing the program. With a minor adjustment of pressing any key and responding immediately to pressing the Enter key, getchar() solves the problem just as well without destroying portability:

#include <stdio.h>

int main(void)
{
    fputs("Press [Enter] to continue...");
    fflush(stdout);
    getchar();

    return 0;
}

One argument against the standard solution is that there might be extraneous junk in the input stream. If that's the case, getchar() will terminate immediately rather than block for user input. The most obvious solution is not to leave extraneous junk in the stream in the first place. That indirectly encourages the good I/O practice of splitting two tasks: input and parsing (the oft recommended combination of fgets() and sscanf(), for example).

Then there's the question of whether this feature is needed in the first place? Why are you trying to pause the program? The answer is invariably a description of a common beginner problem of the console window closing before one can read the final output. However, this makes the assumption that the program will be run either through an IDE that does not support a forced pause without extra code or by double clicking on the executable icon in a windowed system (note that the conio approach is generally limited to Microsoft Windows platforms).

The issue here is that you force the program to be user interactive. With getchar() it can still be automated by piping the requisite newline; an awkward solution, but doable. However, with getch() a client would have to signal a keypress, which is either extremely awkward or impossible, depending on the client. Alternatively the client could kill the process and avoid dealing with your program's unnecessary limitation. All of these are troublesome.

Okay, what about #2? What's wrong with clearing the screen when the program starts? Well, it's either pointless or anti-social, depending on how you run the program.

  • Running from an IDE: When you run a program from an IDE, the IDE will create a new window to host it. Since the window is completely new, there's no existing output in it, and clearing the screen accomplishes nothing except destroying portability. There's no portable way to accurately clear the screen in C.
  • Running from double click: When you double click on the executable icon, a new window is created to host the program. Just like with running from an IDE, there's no existing output to clear.
  • Running from the command line: The command line is where there might be existing output. The command line isn't owned by your program and isn't tied to your program's lifetime. Many programs could have run before it and written output, so what's the problem? The problem is that your program doesn't own that output. How do you know that the user doesn't want to keep it for some reason?

    If the user wants to clear the screen before running your program, they can do so without your "help". If the user doesn't want to clear the screen, I can guarantee that your program will be used once and then removed if it does so. Users don't react well to "helpful" programs deleting their data.

If you truly need a clear screen then the program should use another approach, such as a GUI, file output, or a new command line window (owned by your program). But in my experience, all of these programs that call clrscr() when the program starts don't really need a clear screen. The author's do it because that's how they were taught, but they were taught wrong.

void main()

On hosted implementations, void main can do one of two things:

  • Work correctly if the implementation supports it as an extension.
  • Invoke undefined behavior if the implementation does not support it as an extension.

Those are two extremes, because working correctly is the ideal and invoking undefined behavior is the worst possible thing a C program can do. Given that alone, a wise programmer will never use void main because it's simply too risky. The C standard says that returning int is always valid, will always work correctly, and never invokes undefined behavior. Thus this is the correct definition of main() (when taking no arguments):

int main(void)
{
    return 0;
}

and this, though allowed as an extension, is not:

void main(void)
{
}

And yes, there are accounts of void main breaking a program. It's not simply a theoretical bug.

clrscr();

This is conio misuse #2, but it's also broken in that C (prior to C99) does not allow executable statements to be placed before declarations. Thus this line means one of three things:

  • The code is C90 and fails to compile.
  • The code is C99, is correct, and compiles.
  • The code is C++.

The last is the most worrisome because if you're trying to write C, compiling as C++ might cause problems because there are subtle differences between C and the C subset of C++. People who know to compile as C99 aren't likely to write code like this, so I'd lean toward it being compiled as C++.

printf("Enter Name : ");

The output stream is flushed in three cases:

  1. The stream's buffer is full.
  2. A newline is printed.
  3. fflush() is called.

You can't control the stream's buffer, so #1 is merely trivia. If you'll notice that neither a newline is printed nor is fflush() called, so this prompt is not required to be displayed before the subsequent scanf() blocks for input. Prompts are typically cleaner when both the message and user input are on the same line, so printing a newline is probably not the best option. Instead, a call to fflush(stdout) should be placed between printf() and scanf().

scanf("%s",name);

Hopefully you've learned about buffer overflow at some point, and been told how utterly devastating it can be. When it comes to user input, gets() is the canonical bad function because there's no way to avoid buffer overflow. scanf()'s %s format specifier without a field width is no better than gets() because it doesn't limit the number of characters that will be written to the array. When using %s , always provide a field width. The field width excludes the string's null terminator in the case of scanf(), so you should be using %49s instead of %s .

Another problem is that you failed to check to see if scanf() succeeded. Since name is uninitialized, there's a possibility of scanf() failing before writing any characters. If that happens you'll print an uninitialized array, which invokes undefined behavior. One solution is to initialize name to an empty string, but a better solution is to follow a simple guideline: always check user input for failure.

printf("\n%s",name);

The newline is improperly placed. A lot of beginners like to put a newline first rather than last; I haven't figured out why yet.

getch();

This is conio misuse #1.

There you go. Nearly every line of this program is wrong in some way or other, and that's not taking into consideration that it fails to solve the OP's problem of not allowing embedded whitespace in the name. Here's the code with all above corrections applied:

#include <stdio.h>

int main(void)
{
    char name[50];

    printf("Enter your name: ");
    fflush(stdout);
    
    if (scanf("%49s", name) == 1)
        printf("%s\n", name);
    
    return 0;
}

And this is the code that actually solves the OP's stated problem:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char name[50];

    printf("Enter your name: ");
    fflush(stdout);
    
    if (fgets(name, sizeof name, stdin) != NULL) {
        /* fgets() copies the newline as well; remove it */
        char *newline = strchr(name, '\n');
        
        if (newline != NULL)
            *newline = '\0';
        
        printf("%s\n", name);
    }
    
    return 0;
}
commented: Cn we use this as a cut'n'paste for all other bozo's? ;-) -- Kidding! +17
Member Avatar for HASHMI007

thnkx Narue

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.