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


int main(){
char name[80];
char *searchptr;
int i, t; 


for(i=1; name[i]!=EOF; i++){
printf( "Enter name\n");
scanf("%s", &name[i]);
}

for(t=i; t<=0; t--){
printf(" name[%d] == %s", i, name[t]);

getch();
return 0;
}}

Dani AI

Generated

The original snippet has several mutually related issues (indexing, input method, loop logic and types). and pointed out those problems — below is a small, safe example that reads up to N names (accepts spaces), stops on a blank line or EOF, and then prints what was entered.

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

int main(void) {
    enum { MAX_NAMES = 20, MAX_LEN = 80 };
    char names[MAX_NAMES][MAX_LEN];
    int count = 0;
    int i;

    for (; count < MAX_NAMES; ++count) {
        printf("Enter name (blank to stop): ");
        if (!fgets(names[count], sizeof names[count], stdin))
            break;              /* EOF or read error */
        size_t len = strlen(names[count]);
        if (len && names[count][len - 1] == '\n')
            names[count][len - 1] = '\0';
        if (names[count][0] == '\0')
            break;              /* blank line -> finish input */
    }

    for (i = 0; i < count; ++i)
        printf("name[%d] = %s\n", i, names[i]);

    return 0;
}

Notes and troubleshooting tips:

  • Use fgets (not scanf("%s", ...)) to accept spaces and to avoid buffer overruns. fgets returns NULL on EOF or error so you can stop cleanly.
  • Strip the trailing newline before storing/printing.
  • Keep loop indices simple and consistent: start at 0, increment, and use the recorded count when printing.
  • Avoid nonstandard functions like getch() unless you specifically need them and include the proper header.
  • For an unknown or large number of names, store char * pointers and malloc each string (remember to free later), or use getline where available.

This version is minimal, portable, and fixes the type/loop problems in the original while keeping input safe for real names.

Recommended Answers

All 2 Replies

help plz, i am trying to input some names and then output them

I suggest using a 2D character array

@ line 12:
1. array indexes start at 0
2. since your not using files why use EOF? do yo expect that the user would input a negative value? I believe you can use a much simpler alternative for this


@ line 17:
1. why start at the last value of i then decrement as if you want to view the array backwards?
2. the loop condition won't be met
3. why is the return statement for main at the loop?

Also, you can't put a char value to "%s" (@line14 &18).
name is a char variable;
name is a char array or you may call it string in C);

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.