How to input numbers from console - c

I want to read some numbers from the console. The numbers will appear in this way -
5 1 2 3 4 5
4 5 6 7 8
6 2 3 4 5 6 7
..............
EOF
The starting number represents how many number will appear in that line, i.e., the first number of the first line is 5, so there will be 5 more numbers on this line. The end of input will be denoted by the EOF (end-of-file).
I thought of reading the whole line as a string and then convert them to numbers but I want to know is there any other way to do this.

The 'standard' answer is scanf(). The trouble with the standard answer is that it won't allow you to check that there are the correct number of numbers on a line. So, your idea of reading a line and then converting it piecemeal is much better for error detection.
Take a look at How to use sscanf() in loops; the answer there shows you the basics of what you should do. It isn't an exact duplicate. You will read a first value identifying how many entries are on the line, followed by code to read that many entries into an array, with appropriate diagnostics if the data doesn't match the format claimed for it.
If you are in charge of the data format, you should consider dropping the count field - let the computer count how many values are on the line. Computers are good at counting, and it removes a source of errors to be detected and handled (so it makes the programming easier). (If you do change the input format, your question becomes a duplicate of the linked question.)

Have a look at the documentation of scanf:
int count, current, i;
while(scanf("%d", &count) > 0)
{
for(i = 0; i < count; i++)
{
scanf("%d", &current);
// store current
}
}

Related

How to check scanf two integers in c

I have a problem, that I need to scan two integers in one line divided by a space, so the code looks something like this:
scanf("%d %d",&integer1,&integer2);
And in this code I need to check whether there were scanned two integers. Can someone help me?
Thank you in advance
By default scanf() reads the space there is no meaning in giving space. If you want to read two integers scanf("%d %d",&integer1,&integer2); and scanf("%d%d",&integer1,&integer2); both will help you.
It will accept the following inputs:
1 2
12 22
3 2 5 //EOF
your program will pass only after reading two integers. You don't need to check anything.
To eliminate EOF
By default scanf returns number of values read so make use of it.
if(scanf("%d%d",&integer1,&integer2) != 2)
{
//if more than two values are entered
//perform some error handling
}

How to display output after entering some integers separated by a newline without the use of arrays?

Task:
t denotes the number of inputs, followed by t lines, each containing a single integer n.
For each integer n given at input, display a line with the value of n.
Sample input:
4
1
2
5
3
Sample output:
1
2
5
6
The output should appear after all lines of integer n are taken as input, i.e, it should not display output after each line of input.
How can this be done using a while loop without the use of array to store the input numbers?
while(i<t)
{
scanf("%d",&num);
printf("%d",&num);
i++;
}
This code is working fine if the input numbers n are separated by a space and appears on the same line. But when the input numbers are provided after a newline, it displays the corresponding output after each input value.
Generally such type of input output are used in coding competition where a user is expected to match the expected output to the actual output.
Try pasting the input using a command prompt or online compilers and check it. It is totally fine as the output is as expected.
How does it take if the total input is given at once.
First it reads the t and then it reads the num and prints the number but your printing is actually after the input. This is how the output is checked in a coding competition.
PS: If you want everything after input, use arrays.
If you want to this without using array, then the best way i could think of is recursion. But note, that internally, your values will be stored in the stack frames, and your values will be printed in reverse(because stack is LIFO). Here is how you can do,
void foo(i, t)
{
if(t==i)
return;
int num;
scanf("%d",&num);
foo(++i, t);
printf("%d\n",num);
}
Note, however, that the values will be printed in reverse, as stack is LIFO

how to store matrix from input

I am given matrix in this input format:
-1 2 3\n
5 9 11\n
3 4 5\n
So in words it is: N integers where row is ended by user pressing enter (\n in the example) after each row.
I have to check for valid input so if user enters anything besides numbers and white space, (space, new line, tab '\t' and character - for negative integers), it is invalid (including + sign), output of the program should determine if it is NxN matrix.
The way I am thinking is to read it by characters until last read character is '\n' and store them in 2-dimension array (for future use), save number of stored numbers so I can check in the future if it was NxN.
Is this good approach or is there something smarter?
That seems like a decent approach... but you don't need to store them — you just need to check if it either ends before N rows or after N rows.
If the number of entries per row varies, then return false.
If the matrix ends before the number of rows == the number of columns, return false.
If the number of rows surpasses the number of columns, return false.
If it breaks any of your character rules, return false.
EDIT: MY bad, just pulled a dum-dum and realized you actually wanted to store it and not just check it. The same thing applies, but after reading the first row into an array you made of some maximum size, you can allocate a new 2-dimensional char array with malloc, and then just break if it won't fit for some reason.

How do you scan redirected files in C (STDIN)?

Say I'm calling a program:
$ ./dataset < filename
where filename is any file with x amount of line pairs where the first line contains a string and second line contains 10 numbers separated by spaces. The last line ends with "END"
How can I then start putting the first lines of pairs (string) into:
char *experiments[20] // max of 20 pairs
and the second lines of the pairs (numbers) into:
int data[10][20] // max of 20, 10 integers each
Any guidance? I don't even understand how I'm supposed to scan the file into my arrays.
Update:
So say this is my file:
Test One
0 1 2 3 4 5 6 7 8 9
END
Then redirecting this file would mean if I want to put the first line into my *experiments, that I would need to scan it as such?
scanf("%s", *experiments[0]);
Doing so gives me an error: Segmentation fault (core dumped)
What is incorrect about this?
Say my file is simply numbers, for ex:
0 1 2 3 4 5 6 7 8 9
Then,
scanf("%d", data[0][0]); works, and will hold value of '1'. Is there an easier way to do this for the whole line of data? i.e. data[0-9][0].
find the pseudo-code, code explains how to read the input
int main()
{
char str[100]; // make sure that this size is enough to hold the single line
int no_line=1;
while(gets(str) != NULL && strcmp(str,"END"))
{
if(no_line % 2 == 0)
{
/*read integer values from the string "str" using sscanf, sscanf can be called in a loop with %d untill it fails */
}
else
{
/*strore string in your variable "experiments" , before copying allocate a memory for the each entry */
}
no_line++;
}
}
The redirected file is associated with the FILE * stdin. It's already opened for you...
otherwise, you can treat it the same as any other text file, and/or use the functions that are dedicated to standard input - with the only exception that you cannot seek in the file and not retrieve the size of the input.
For the data sizes you're talking about, by far the easiest thing to do is just slurp all of the content into a buffer and work on that: you don't have to be super-stingy, just make sure that you don't overrun.
If you want to be super-stingy with memory, preallocate a 4kB buffer with malloc(), progressively read() into it from stdin, and realloc() another 4kB every time the input exceeds what you've already read. If you don't care so much about being stingy with memory (e.g. on a modern machine with gigabytes of memory), just malloc() something much bigger than the expected input (e.g. a megabyte) and bug out if the input is more than that: this is far simpler to implement but less general/elegant.
You then have all of the input in a buffer and you can do what you like with it, which depends too strongly on the format of the input for me to say how you should approach that part.

How To Read Input From Test Case File in C

Currently i am enrolled in NPTEL course. There i need to make c program as assignment.
Qusetion is in this format :-
Write a program that reads numbers which are in the range 0 to 100, till it encounters -1. Print the sum of all the integers that you have read before you encountered -1
INPUT:
A sequence of integers separated by whitespace. There may be other integers following -1.
How do i read input from test case file? plz help
I have used following code :-
while((n=scanf("%d",&n1))!=EOF)
{
printf("%d",n);
}
Loop is iterating properly ie if test case 1 has 5 input its running for 5 times. If test case 2 has 2 input hen iterating 2 time. But it is unable to read input . Please Help.
You're printing n which is the number of items read. You need to print n1.
EDIT:
Your check for the while loop is incorrect. You need to check the value that is read i.e. n1 but once again, you're using the value of n to check for EOF. You should be checking for -1 as well since that's what you want right?

Resources