How to test my program against an input test case file - c

I was participating in some coding contests and luckily my code also ran. However my solution was not expected because i was wrong with the pattern of taking input.
The question involved taking in an integer as an input and performing some operation and returning a different or same integer. I do not have any problem with the program, I just don't know how to code so as to take inputs like this
Input
The input will contain several test cases (not more than 10).
Each test case is a single line with a number n, 0 <= n <= 1 000 000 000.
It is the number given as input.
Output
For each test case output a single line, containing the integer returned.
Example
Input:
12
2
Output:
13
2
My code is
#include <stdio.h>
int functionReturningInteger(int n)
{
// implementation
........
return num;
}
int main(void)
{
int number;
//printf("Enter the number: ");
scanf("%d",&number);
printf(functionReturningInteger(number));
return 0;
}
How am i supposed to know how many inputs they will give ( although they do provide a maximum limit). And if i use an array to store these inputs whose size is equal to the maximum limit, how do i check the size of an integer array in c ?
I will appreciate anybody helping out with a small piece of code. Also if am able to test it against an input test file and generate an "output.txt" (output file). I already have the desired output file "des.txt". Then how can i match whether both the files are same or not ?

#include <stdio.h>
int scanned;
while((scanned = scanf("%d", &number)) != EOF) {
printf("%d\n", functionReturningInteger(number));
}
If scanf detects the end of input before a successful conversion, it returns EOF.
For the other questions, redirect input and output,
$ ./your_prog < input.txt > output.txt
and compare
$ comp output.txt des.txt

You could read line by line until there is nothing to read from file. This way you don't need to know how many inputs is given.
There is no default way to track array size in C.
To match files you can use diff on Linux\Unix os.

Related

Limiting the type length of the user on C

My code asks a the 10 digit number, it reads it as a string, pass it to another function that checks if the user's input is a real number and has no characters or symbols with ASCII, and then if it's good, with atof it changes the string into a number for a variable.
I want the user to only introduce 10 digits/characters on the input console, I mean, if the user would put a 11 character for example, the console just don't grab it, or in the case this is impossible for C, make that if the user put more than 12 characters on the input, then the program launches an error message saying it exceeds the limit, the problem is, when i tried to use this method, for example if i put some big numbers like a 40 digit number, then the program goes crazy and send just incomprehensible results like "1.#J", or if I put a character in middle of the numbers, then it sends the corresponding error message i set for the user to not put characters, but it still grabs part of the number and accept it as it is nothing wrong, here's the main of code I tried:
int main() {
char chain[10];
float N;
int valid=0;
do{
printf("introduce real numbers: ");
fgets(chain, sizeof(chain), stdin);
if( chain[strlen(chain)-1] == '\n')
chain[strlen(chain)-1] = '\0';
valid=validate_numbers(chain);
}while(valid==0);
N=atof(chain);
printf("float number is: %.2f", N);
getche();
return 0;
}
Here's the rest of the code for more extense check: Pastebin
And sorry if there's some novice errors or the question is plain simple, im quite new programing.
Change this:
char chain[10];
to this:
char chain[11]; // +1 for the NULL terminator
since C-strings should be NULL terminated, thus we need one cell reserved for the NULL-terminator in our array (which will store our string).
I mean, if the user would put a 11 character for example, the console just don't grab it
Not possible in C.
or in the case this is impossible for C, make that if the user put more than 12 characters on the input, then the program launches an error message saying it exceeds the limit.
Yes, let's do that! Read the string, and if the length of it is more than 10 characters, then print an error message.
Allow chain array to be of size 12 (10 for the maximum length of the valid input, 1 for an extra character (if any) and 1 for the NULL-terminator), so that we can store the extra character, if any.
Example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char chain[12];
printf("introduce real numbers:\n");
fgets(chain, sizeof(chain), stdin);
chain[strcspn(chain, "\n")] = '\0';
if(strlen(chain) > 10)
{
printf("Error: Maximum length of chain is 10! Exiting..\n");
return 1;
}
return 0;
}
Note: You could use EXIT_SUCCESS and EXIT_FAILURE, instead of plain numbers (1 and 0 respectively): Should I return 0 or 1 for successful function?
Irrelevant to OP's question: In the full version of your code though, there is a plethora of problems, such as this top line of code int valid=validate_numbers(char number[]);, which wishes to declare the method. It should be just validate_numbers(char number[]);. The same holds true for the definition of the method too. Make sure you go through all your code again, and read the messages the compiler gifts to you. :)
What about using scanf instead of fgets? This should read 9 characters and save them as a string:
scanf("%9s" , &chain)
I'd suggest reading https://en.m.wikipedia.org/wiki/Scanf_format_string and man pages as well.

c program taking multiple inputs instead of one input [duplicate]

I'd like to understand why the program allows me to input 3 integers when I have defined SIZE as 2. And when it returns the array it only returns two numbers NOT the three I have entered.Thanks for your help.
//C How to Program Exercises 2.23
#include <stdio.h>
#include <conio.h>
#define SIZE 2
int main (void){
int myArray[SIZE];
int count;
printf("Please enter 5 integers\n");
for (count=1;count<=SIZE;count++){
scanf("%d\n",&myArray[count]);
}
for (count=1;count<=SIZE;count++){
printf("The values of myArray are %d\n",myArray[count]);
}
getch();
return 0;
}
Your loops should be
for (count=0;count<SIZE;count++)
Array indexing is 0 based in C.
Since you have a whitespace chatacter (\n) in scanf() call, it waits for you input a non-whitespace character to complete each call. Remove the \n:
for (count=0;count<SIZE;count++){
scanf("%d",&myArray[count]);
}
C arrays are indexed starting from 0, not from 1. C does not automatically perform bounds checking on array accesses, and indeed, your code is well-formed. However, its runtime behavior is undefined on account of its using an array element expression to write outside the bounds of that array, and, separately, on account of its using an array element expression to read outside the bounds of that array.
Inasmuchas the program definitely exhibits undefined behavior on every run, absolutely nothing can be said about what it should do. If in practice you observe the input loop iterating thrice, then a likely explanation is that the second iteration overwrites the value of the count variable. Given the order in which the variables are declared, this is a plausible manifestation of the undefined behavior in play.
The output loop, on the other hand, iterates exactly the number of times you told it to do: once with count == 1, and once more with count == 2. This is by no means guaranteed given the general undefinedness of an execution of your program, but it is about the least surprising behavior I can think of.
why the program allows me to input 3 integers
This loop runs exactly 2 times:
for (count=1;count<=SIZE;count++){
scanf("%d\n",&myArray[count]);
}
But as you used \n in the scanf(), this scanf() waits until you give any whitespace.
Proper Input code:
for (count=0;count<SIZE;count++){
scanf("%d",&myArray[count]);
}
And when it returns the array it only returns two numbers
Your original output code prints first number correctly, But your second number is garbage value.
Proper Output Code:
for (count=0;count<SIZE;count++){
printf("The values of myArray are %d\n",myArray[count]);
}
So Full Code goes like this:
//C How to Program Exercises 2.23
#include <stdio.h>
#include <conio.h>
#define SIZE 2
int main (void){
int myArray[SIZE];
int count;
printf("Please enter 5 integers\n");
for (count=0;count<SIZE;count++){
scanf("%d",&myArray[count]);
}
for (count=0;count<SIZE;count++){
printf("The values of myArray are %d\n",myArray[count]);
}
getch();
return 0;
}

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

issues with C Program to convert user input to Integer and then Integer to (HEX, Bin, Alpha)

#include <stdio.h>
#include <stdlib.h>
int main(void) {
/*holds the number to be converted between methods.*/
char convNumber;
/*storageInt */
int storageInt;
puts("put text in here to convert to bin");
while ((convNumber = getchar()) != '$') {
storageInt = storageInt * 100 + convNumber;
}
printf("%d", &storageInt);
return 0;
}
ok, Above is the code that is giving me problems. I'm new to C and this is a school project.
Question:
How do i convert user input with a delimiting character '$' into an integer which I can store and print or use to convert to hex or binary. At the bottom of the page is a full view of what my output should eventually look like to give an idea of the type of input required.
Background and assignment info:
I keep getting unexpected output when attempting to print the user input as an integer. My goal is to have blocks of 2 integers, representing ASCII, in order from 0 to N (N is the end of user input). User input is designated as finished by typing $. What am I doing wrong?
When going through the program choosing "A", "A", and then finally "A$" ($ for terminating the program) I get 2337412 instead of the expected 65 ascii for 'A'.
So please help me understand this so I will do better on subsequent assignments (looking for explanations). Thanks in advance!
END RESULT:
Welcome to the Coder!
Choose Input (H,A,B,Q): A
Choose Output(H,A,B): H
Enter your alpha input.
Hi! Bye! $
486921204279652120
Choose Input (H,A,B,Q): H
Choose Output(H,A,B): B
Enter your hex input.
486921204279652120$
010010000110100100100001001000000100001001111001011001010010000100100000
Choose Input (H,A,B,Q): B
Choose Output(H,A,B): A
Enter your bin input.
You are printing storageInt's memory address. You use memory addresses only in scanf for reasons you'll find obvious after you learn more. Strings are an exception, but this is not a string.
Do this:
printf("%d", storageInt);

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