-2
#include<stdio.h>
int main() {
    int index=0;
    char str[1000];
    char c;
    while((c=getchar())!='/')  {
       while((c=getchar())!='\n') {
          scanf("%c",&str[index]);
          index++;
       }
       str[index]='\n';
       index++;
    }
    str[index]='\0';
    printf("%s",str);
    return 0;
}

I am giving input in the form of multiple lines ,and I want to display the output in similar fashion as input provided ,I am using '/' character as the end of input ,now I am not getting the output ,how to resolve this issue ?

Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
user123
  • 271
  • 1
  • 10

2 Answers2

2

When reading characters from stdin, in your case, you have three conditions to protect against if you want to terminate the read on '/':

  1. index + 1 < 1000 (to prevent overrun and preserve space for the nul-terminating char)
  2. (c = getchar()) != '/' (your chosen terminator); and
  3. c != EOF (you don't want to read after EOF is set on the stream)

Putting those pieces together, you could simply do:

#include <stdio.h>

#define MAXC 1000   /* define a constant (macro) for max chars */

int main (void) {

    int c, idx = 0;
    char str[MAXC] = "";    /* initialize your array (good practice) */

    /* read each char up to MAXC (-2) chars, stop on '/' or EOF */
    while (idx + 1 < MAXC && (c = getchar()) != '/' && c != EOF)
        str[idx++] = c; /* add to str */

    str[idx] = 0; /* nul-terminate (optional here if array initialized, why?) */

    printf ("%s", str);

    return 0;
}

(I would encourage a putchar ('\n'); after the printf (or simply add a '\n' to the format string) to protect against input without a final POSIX end-of-line, e.g. in the event of a stop on '/', or on reaching 1000 chars, or reading from a redirected file that does not contain a POSIX EOL)

Example Input File

$ cat ../dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.

Example Use/Output

$ ./bin/getchar_io <../dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.

Look things over and let me know if you have any questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
1

Why don't you just use this? :

#include <stdio.h>
int main() {
int index=0;
char str[1000];
char c;
while((c=getchar())!='/')  {
  str[index] = c;
  index++;
}
str[index]='\0';
printf("%s",str);
return 0;
}
Mehdi
  • 47
  • 5