Your task is to write a program that repeatedly reads bytes from stdin, searching for the byte specified on the command line in decimal, and returning the byte number of the first occurrence (starting from zero) if found or -1 if not found. You must use the getchar function for input. This should be in C
Example:
MyPrompt> findByte 65
FEDCBAXYZabc
5
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc == 2) { char ch; int index = 0, result = -1; int n = atoi(argv[1]); while ((ch = getchar()) != EOF) { if (ch == n) { result = index; } ++index; } printf("%d\n", result); } else { printf("Please provide a number as command line argument\n"); } return 0; }
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc == 2) { char ch; int index = 0, result = -1; int n = atoi(argv[1]); while ((ch = getchar()) != EOF && ch != '\n') { if (ch == n) { result = index; } ++index; } printf("%d\n", result); } else { printf("Please provide a number as command line argument\n"); } return 0; }
Get Answers For Free
Most questions answered within 1 hours.