Here is a solution to a CODECHEF Problem "INTEST", which basically tests how fast IO operation is done by a code.
Input
The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each.
Output
Write a single integer to output, denoting how many integers ti are divisible by k.
The following code segment is the fastest C Code submitted so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 65535
int main(int argc, char *argv[])
{
char buffer[SIZE];
unsigned long n, k, input, count;
int c, i;
count = 0;
scanf("%lu %lu\n", &n, &k);
input = 0;
while ((c = fread (buffer, sizeof (char), SIZE, stdin)) > 0)
{
for (i = 0; i < c; i++)
{
if (buffer[i] == '\n')
{
//printf("%d\n", input);
if ((input % k) == 0)
{
count++;
}
input = 0;
}
else
{
input = (input * 10) + (buffer[i] - '0');
}
}
}
printf("%lu\n", count);
return 0;
}
They said that fread() offers a faster IO than scanf as fread() does a buffer IO. But when I compile and run it on my own computer(CODEBLOCKS) and give it a few inputs from the console[Note: I am not piping the input file], suppose I enter 4 3 on the first line denoting that 4 more lines follow. But fread() is not even bothering to accept the 4 more lines and after taking one more input basically the program outputs a 0 if I enter a number divisible by 3 or 1 if the number enter is not divisible by 3 and just terminates.
Why is fread() terminating before accepting all the inputs?
In case of file IO, we can be sure that fread() will read until buffer is full or a file terminator is encountered. But in case of stdin, how long will fread() wait for the user to enter inputs?
Why the program is using a buffer of SIZE 65536?
When the input comes from a terminal, the terminal driver hands data over after each line, and fread() only returns what's available. After the scanf(), the first call to fread() will likely return just one byte, the newline left behind by scanf(). Thereafter, each call will read a single line, because that's the way the terminal driver works.
By contrast, if the input is a regular file, then the fread() call will return as many characters as are available, up to the size of the buffer, completely ignoring newlines as special cases.
If the input is a pipe, then it will read what is available in the pipe at any given time, which might or might not be multiple lines of data, depending on how it is written and whether the reading code keeps up with the writing code.
#include<stdio.h>
int main(){
int i,n,k,m[50],count;
printf(" ");
scanf("%d %d",&n,&k);
count=0;
for(i = 1; i <= n; i++){
printf(" \n");
scanf("%d",&m[i]);
if(m[i] % k==0){
count=count + 1;
}
}
printf("ans=%d",count);
return 0;
}`enter code here`
Related
I want to write a program in C that fills an array p[MAX][N] of strings
I used this but i dont know which is the null string to enter when i give input.
#include <stdio.h>
#include <string.h>
#define R 3
#define C 8
int main()
{
int i;
char strings[R][C];
printf("***Table of Strings - Names***\n\n");
for(i=0;(i<R && gets(strings[i]));i++)
;
if(i==R)
printf("\n**Table Full - input terminated \n");
for(i=0;i<R;i++)
puts(strings[i]);
return 0;
}
First, never use gets(). It is inherently dangerous as it doesn't do any bounds checking on the memory you pass to it. Use fgets() instead:
for (i = 0; i < R && fgets(strings[i], C, stdin); ++i);
Note that fgets() will leave any new line ('\n') in the input at the end of the string, assuming that the whole line can fit in your buffer. If the whole line can't fit in your buffer, then it reads as much as can fit into your buffer (leaving room for and always appending a nul terminator), stops reading the input at that point and leaves the rest of the input on the stream. With C being so small in your program, such an occurrence is quite likely.
Alternatively, you could use getline() if it's available on your platform:
char *strings[R] = { 0 };
size_t cap;
for (i = 0; i < R && 0 <= getline(&strings[i], (cap = 0, &cap), stdin));
if (i == R)
printf("\n**Table Full - input terminated \n");
for (i = 0; i < R && strings[i]; ++i)
puts(strings[i]);
/* program done; clean up strings */
for (i = 0; i < R && strings[R]; ++i)
free(strings[R]);
getline() automatically dynamically (re)allocates the memory necessary to fit the next line from the input stream. It also leaves any new line ('\n') in the input at the end of the string.
Second, ctrl-D is typically used terminate the input to a program from a terminal.
It worked. I changed it to this
int main()
{
int i,j,max,thesi,sum=0,countCH=0,mikos=0;
char strings[R][C];
printf("***Table of Strings - Names***\n\n");
for(i=0;(i<R && fgets(strings[i],C,stdin ));i++)
;
if(i==R)
printf("\n**Table Full - input terminated \n");
for(i=0;i<R;i++)
fputs(strings[i],stdout);
//Euresh megistou string
max=0;
sum=0;
for(i=0;i<R;i++)
{
mikos=strlen(strings[i])-1;
sum+=mikos;
if(mikos>max)
{
max=mikos;
thesi=i;
}
}
printf("\nTo string me to megalitero mikos einai auto pou brisketai sthn %d seira \nkai einai to %s \nme mhkos %d",thesi+1,strings[thesi],max);
printf("\nO pinakas me ta strings periexei %d xaraktires\n",sum);
return 0;
}
It works just fine only that strlen counts all the chars of the string including null char why is that i dont get it?
I want to store a series of integers till i press an enter in an array.How can i implement that
Input:
1(tab space)2(tab space)3(tab space)4(tab space)enter
i tried doing this
#include<stdio.h>
main()
{
int i,j,c,d;
int a[5];
for(i=0;i<2;i++){
j=0;
while((d=scanf("%d",&c))==1){
a[j]=c;
j=j+1;
}
}
}
I dont know how scanf works and using scanf return value.Please explain how i can store this input if its not impossible to do so with scanf and also
2)What else can be used inside scanf along with %d ?
I have a file with 200 rows with numbers like this
(NOTE: each row has varied number of values but all numbers are less than 200)
1\t2\t3\t4\t5\t
2\t3\t4\t5\t6\t7\t8\t
11\t12\t13\t
.
.
200
... so i have to store this as an adjacency list representation
For the first part of your question. scanf() returns number of elements successfully read but it is of no use here and you can just scan in a loop and scanf() will pick your integers in a line when you press enter.
#include <stdio.h>
int main(void) {
int a[5];
int i, n;
for(i=0;i<5;i++)
{
if(scanf("%d",&a[i]) != 1)
{
printf("Value not read correctly\n");
break;
}
}
n = i;
for(i=0;i<n;i++)
printf("%d\n",a[i]);
return 0;
}
For the second question you have to do something line
1.Read a line from your file using fgets()
2.Break your line using strtok() with tab as delimiter.
3.Now convert each token to integer using atoi()
4.Now do whatever you want with the integer. i.e. create a node add your integer to the node
Let's make some reasonable assumptions about the width of each row.
These assumptions are useful for simple code, though not needed in general.
#define LINE_WIDTH_MAX 1000
#define INTS_PER_LINE_MAX 100
#define ROWS_PER_FILE (200 /* given by OP */)
Read each row with fgets(), then scan. Could use strtol(), sscanf() or various approaches.
This method uses sscanf() and "%n" to determine when the next number might follow.
int row;
for (row = 0; row < ROWS_PER_FILE; row++) {
char buf[LINE_WIDTH_MAX + 2];
if (fgets(buf, sizeof buf, stdin) == NULL) {
break; // Handle EOF or IO error
}
int num[INTS_PER_LINE_MAX];
char *p = buf;
for (int i = 0; i<INTS_PER_LINE_MAX; i++) {
int n = 0;
if (1 != sscanf(p, "%d %n", &num[i], &n)) {
break;
}
p += n;
}
if (*p) Handle_GarbageInLIne();
// do something with the `i` numbers
}
Notes:
Advise never use scanf()/
I have a program that reads a file from command line (file that consists of integers - see below), puts it into an array and then prints the array.
#include <stdio.h>
#include <stdlib.h>
#define SIZEBUFF 1024
int main (int argc, char *argv[])
{
if (argc < 2)
{
printf("Missing file\n");
return (EXIT_FAILURE);
}
FILE *file = fopen (argv[1],"r");
int integers [144]; //Array that input is stored
char buffer[SIZEBUFF];
int count = 0;
while (fgets(buffer,sizeof (buffer),file) > 0){ // !=EOF gives seg. fault if used
integers[count] = atoi(buffer);
count++;
}
fclose(file);
printf ("The contents of integer array are: \n");
int j;
for (j = 0; j < 144;j++) printf ("%d\t",integers[j]);
return (EXIT_SUCCESS);
}
NOTE: Real file consists of 144 integers. I just took the first 12
How can I print just the numbers that exist in the file?
This problem is because you wrote code assuming that fgets() reads a single integer from file on each call. But its not so if the integers are stored on same line.
fgets() stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
So here fgets is reading more than one integer at a time from file so atoi() is not getting the integers in file too.
you can use fscanf() to read the integers directly,
fscanf(file,"%d",&integers[count]);
you can loop through this statement 144 times since you know the number of integers in the file or can use,
fscanf (file, "%d", &integers[count]);
while (!feof (file))
{
fscanf (file, "%d", &integers[++count]);
}
You could use fscanf just as you would use scanf to read 144 integers from the console.
You should use fscanf to read integers from the file into the array.
int count = 0;
while(fscanf(file, "%d", &integers[count++]) == 1)
; // the null statement
int j;
for(j = 0; j < count; j++)
printf("%d\t", integers[j]);
These are the directions:
Read characters from standard input until EOF (the end-of-file mark) is read. Do not prompt the user to enter text - just read data as soon as the program starts.
Keep a running count of each different character encountered in the input, and keep count of the total number of characters input (excluding EOF).
I know I have to store the values in an array somehow using the malloc() function. I have to organize each character entered by keeping count of how many times that particular character was entered.
Thanks for the help!
Actually, since you are reading from standard input, there are at most 256 different possibilities. (You read in a char). Since that's the case, you could just statically allocate 256 integers for counting. int charCount[256]; Just initialize each value to 0, then increment each time a match is input.
Alternatively, if you must have malloc, then:
// This code isn't exactly what I'd turn in for homework - just a starting
// point, and non-tested besides.
int* charCount = (int*) malloc(sizeof(int) * 256); // Allocate 256.
for (int i = 0; i < 256; i++) charCount[i] = 0; // Initialize to 0.
// Counting and character input go here, in a loop.
int inputChar;
// Read in inputChar with a call to getChar(). Then:
charCount[inputChar]++; // Increment user's input value.
// Provide your output.
free(charCount); // Release your memory.
Here is a possible solution:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int count[256] = {0};
char *l, *lp;
while (scanf(" %ms", &l) != EOF) {
for (lp = l; *lp; lp++)
count[(int)*lp]++;
free(l);
}
for (int i = 0; i < 256; i++) {
if (isprint(i) && count[i])
printf("%c: %d\n", i, count[i]);
}
exit(EXIT_SUCCESS);
}
Compile:
c99 t.c
Run:
$ ./a.out
abc
ijk
abc
<-- Ctrl-D (Unix-like) or Ctrl-Z (Windows) for EOF
a: 2
b: 2
c: 2
i: 1
j: 1
k: 1
I'm kind of new to C, and the input reading is really confusing me. I'm trying to initialize an array of size 4, but sometimes the user will enter valid input of 3. In Java, I could check the length of the input and add conditionals, but I'm not sure how this works in C.
main(void){
char str[N];
int i;
for(i = 0; i < N; i++){
scanf("%c", &str[i]);
}
for(i = 0; i < N; i++){
printf("%c\n", str[i]);
}
}
Right now, if I input 4 or more, it works fine. If I input 3, it breaks. I'd like it to handle both 3 or 4 characters.
Actually, the root of the problem is: I'm trying to figure out a way in C to read in a 24-hour-clock time, and add it to a 24-hour-clock duration. Should I be approaching this an entirely different way?
Thanks,
The short answer is: you can't.
Using scanf() is particularly dangerous because of this if you want to read in a string (%s); if the user enters more input than your buffer can hold, you have a buffer overflow on your hands.
fgets() on the other hand, allows you to specify the max number of bytes you will read, preventing you from overflowing the buffer.
Here's a quick example on how you'd write a function for some input that verified that the input was within a specified length and was a complete line (ending with \n - this routine discards the \n from the input):
void getInput(char *question, char *inputBuffer, int bufferLength)
{
printf("%s (Max %d characters)\n", question, bufferLength - 1);
fgets(inputBuffer, bufferLength, stdin);
if (inputBuffer[strlen(inputBuffer) -1] != '\n')
{
int dropped = 0;
while (fgetc(stdin) != '\n')
dropped++;
if (dropped > 0) // if they input exactly (bufferLength - 1)
// characters, there's only the \n to chop off
{
printf("Woah there partner, your input was over the limit by %d characters, try again!\n", dropped );
getInput(question, inputBuffer, bufferLength);
}
}
else
{
inputBuffer[strlen(inputBuffer) -1] = '\0';
}
}
int main()
{
char firstAnswer[10];
getInput("Go ahead and enter some stuff:", firstAnswer, 10);
printf("Okay, I got: %s\n",firstAnswer);
}
scanf() allows the use of maximum width specifiers:
So scanf("%3s", buffer) reads at most 3 characters + 1 NUL terminator.