0

Sorry for asking very simple question.I'm new to coding.
Input txt file

5,3
001
110
111
110
001

I need to print the output as

U1: 001
U2: 110
U3: 111
U4: 110
U5: 001

Upto now I was able to print the contents with this:

  #include <stdio.h>
  void main() {
    FILE *fopen(), *fp;
    int c;

    fp = fopen("read.txt","r");
    c = getc(fp) ;

    while (c!= EOF) {
      putchar(c);
      c = getc(fp);
    }

    fclose(fp);
  }

Can Anybody tell how should I proceed?

3
  • I'm reading but can u show some direction. Commented Nov 3, 2011 at 14:09
  • One tip: use more than 1 space for indentation. It's rather hard to read your code. Commented Nov 3, 2011 at 14:12
  • 1
    @ILLUMINATI7590, Kernighan and Ritchie, for instance. You really sound like you need to make some effort of your own here. Commented Nov 3, 2011 at 14:12

2 Answers 2

2

Most of your work is done inside the while loop.
But you're not doing enough work ...
a) you need to count lines
b) you need to print the "U#"

Suggestion: create a variable for the line counting business and rewrite your loop to consider it. Here's a few snippets

int linecount = 0;


printf("U%d: ", linecount)


if (c == '\n') linecount += 1;

Oh! You really shouldn't add the prototype for fopen yourself. It is already specified with #include <stdio.h>.

And well done for declaring c as int. Many people do the error of declaring it char which is incompatible with EOF and all the range of characters

Sign up to request clarification or add additional context in comments.

Comments

0

I would read the data a line at a time with fgets. When you have a complete line in a buffer, it'll be pretty easy to get fprintf to put in your line header with a format like "U%d: %s\n".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.