0

I would like to see line number in the console when it asks for input.

Something like:

1 foo
2 bar
3 baz

Here 1 was shown in the prompt and I enter any input and hit enter Then the next number shows up and I do the same.

Any simple help for this in C for a beginner?

user2656
  • 33
  • 4
  • 1
    Have a counter variable and increment it with every input you ask for. You'll then print it explicitly with every new input, something like: `unsigned int n = 0; for(;;) { /*... */ printf("%u", ++n); /* read input */ }` – Aconcagua Jun 19 '21 at 09:42

2 Answers2

2

This will might help you.

#define _CRT_SECURE_NO_WARNINGS

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

int main() {
    int lineNo = 0;
    char name[256];

    do {
        printf("%d ", ++lineNo);
        scanf("%s", name);

    } while (strlen(name) > 0);

    return 0;
}
Denis Turgenev
  • 138
  • 1
  • 9
0

I think I tried the easiest way I know for this. You can do this with the help of a 2D array. Following is the code for this:

#include<stdio.h>
main()
{
char arr[3][1];
int i,j;
for(i=0;i<3;i++){
    for(j=0;j<1;j++){
        printf("%d ",i+1);
        scanf("%s",&arr[i][j]);
        }
}

}

You can change the size of the array as per the number of inputs you want. This code is taking 3 inputs, you can change it to as per your input needs.

LucyRage
  • 28
  • 6
  • `char arr[3][1];` is too small and leads to undefined behavior with `scanf("%s",&arr[i][j]);`. The application of `for(j=0;j<1;j++){` is amiss as no need to loop for each character. – chux - Reinstate Monica Jun 19 '21 at 13:07