Writing(in a file) and printing statistics - c

My task is to create a C program that opens a .c file in which the user then writes some text then said text is printed along with the number of (){}/ and the percentage ratio comments:whole text of the C program.
So far I've this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int k, j, m, n, l, z, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
char str[10000], chh, chhh;
char ch, file_name[75];
FILE *fp;
printf("Enter the name of file you wish to see with extension .c or .txt\n");
gets_s(file_name);
fp = fopen_s(file_name, "r"); // reads the file
if (fp == NULL)
{
perror("Error while opening the file.\n");
_getche();
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); //prints out the text
int i = 0;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
str[i] = ch;
i++;
}
int fsize = i;
// code above opens up the symbols of the file, code below searches for specific symbols
int count = 0;
printf("\nEnter the character to be searched : "); //which symbol to search
scanf_s("%c", &chh);
for (i = 0; i < fsize; i++) {
if (str[i] == chh)
count++;
}
if (count == 0)
printf("\nCharacter '%c' is not present", chh); //if there isn't one
else
printf("\nOccurence of character '%c' : %d", chh, count); //prints their number if there is
for (k = 0; k<fsize; k++) {
if (str[k] == '>')
count1++;
}
for (j = 0; j<fsize; j++) {
if (str[j] == '<')
count2++;
}
for (m = 0; m<fsize - 1; m++) {
if (str[m] == '=' && str[m + 1] == '=')
count3++;
}
for (n = 0; n<fsize - 4; n++) {
if (str[n] == 'e' && str[n + 1] == 'l' && str[n + 2] == 's' && str[n + 3] == 'e')
count4++;
}
for (l = 0; l<fsize - 2; l++) {
if (str[l] == 'i' && str[l + 1] == 'f')
count5++;
}
int br;
br = count4 + count5;
printf("\nOccurence of character '%c' : %d", '>', count1);
printf("\nOccurence of character '%c' : %d", '<', count2);
printf("\nOccurence of character == : %d ", count3);
printf("\nOccurence of character else : %d ", count4);
printf("\nOccurence of character if: %d \n", count5);
printf("\nobsht broi if+else: %d ", br);
fclose(fp);
return 0;
}
It prints out the text inside a file, searches for a specific character you want and prints out its occurrence.
PS: when I try to run it on my PC, Visual Studio spits out a bunch of errors and warnings. I'm puzzled as to how to get rid of them.
Errors image
Thanks !

Using GCC I was able to compile this by changing a few methods.
changed gets_s to gets(file_name) which produces a warning that this is an unsafe function.
changed _getche() to getchar()
changed scanf_s() to scanf()
change fopen_s() to fopen()
This code compiled and ran using GCC on Linux
#include <stdio.h>
#include <stdlib.h>
int main()
{
int k, j, m, n, l, z, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
char str[10000], chh, chhh;
char ch, file_name[75];
FILE *fp;
printf("Enter the name of file you wish to see with extension .c or .txt\n");
gets(file_name);
fp = fopen(file_name, "r"); // reads the file
if (fp == NULL)
{
perror("Error while opening the file.\n");
getchar();
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); //prints out the text
int i = 0;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
str[i] = ch;
i++;
}
int fsize = i;
// code above opens up the symbols of the file, code below searches for specific symbols
int count = 0;
printf("\nEnter the character to be searched : "); //which symbol to search
scanf("%c", &chh);
for (i = 0; i < fsize; i++) {
if (str[i] == chh)
count++;
}
if (count == 0)
printf("\nCharacter '%c' is not present", chh); //if there isn't one
else
printf("\nOccurence of character '%c' : %d", chh, count); //prints their number if there is
for (k = 0; k<fsize; k++) {
if (str[k] == '>')
count1++;
}
for (j = 0; j<fsize; j++) {
if (str[j] == '<')
count2++;
}
for (m = 0; m<fsize - 1; m++) {
if (str[m] == '=' && str[m + 1] == '=')
count3++;
}
for (n = 0; n<fsize - 4; n++) {
if (str[n] == 'e' && str[n + 1] == 'l' && str[n + 2] == 's' && str[n + 3] == 'e')
count4++;
}
for (l = 0; l<fsize - 2; l++) {
if (str[l] == 'i' && str[l + 1] == 'f')
count5++;
}
int br;
br = count4 + count5;
printf("\nOccurence of character '%c' : %d", '>', count1);
printf("\nOccurence of character '%c' : %d", '<', count2);
printf("\nOccurence of character == : %d ", count3);
printf("\nOccurence of character else : %d ", count4);
printf("\nOccurence of character if: %d \n", count5);
printf("\nobsht broi if+else: %d \n", br);
fclose(fp);
return 0;
}

Please find my findings below.
gets_s(file_name); -> i dont think this is correct. gets_s Takes up 2 argument and not 1 please use gets instead and try it out or simple scanf to check if it is working.
2._getche() Please use #include header file for that function. Using it would avoid this issue.
fopen_s -> Fopen has invalid set of arguments. U need a file pointer as the first argument. Please re-frame the function used. Better go for fopen which has 2 arguments.
scanf_s -> has an argument(parameter) where you can specify the buffer size. Hence the above code sacnf_s function u have used is syntaticaly wrong. Please change it accordingly.
Please find the changed code which is commonly used. I have taken the liberty of changing the gets_s to gets, fopen_s to fopen and scanf_s to scanf and have build it. No errors. Please find the code below for your reference.
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
FILE *fp;
int main()
{
int k, j, m, n, l, z, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
char str[10000], chh, chhh;
char ch, file_name[75];
printf("Enter the name of file you wish to see with extension .c or .txt\n");
gets(file_name);
fp = fopen(file_name, "r"); // reads the file
if (fp == NULL)
{
perror("Error while opening the file.\n");
getchar();
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); //prints out the text
int i = 0;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
str[i] = ch;
i++;
}
int fsize = i;
// code above opens up the symbols of the file, code below searches for specific symbols
int count = 0;
printf("\nEnter the character to be searched : "); //which symbol to search
scanf_s("%c", &chh);
for (i = 0; i < fsize; i++) {
if (str[i] == chh)
count++;
}
if (count == 0)
printf("\nCharacter '%c' is not present", chh); //if there isn't one
else
printf("\nOccurence of character '%c' : %d", chh, count); //prints their number if there is
for (k = 0; k<fsize; k++) {
if (str[k] == '>')
count1++;
}
for (j = 0; j<fsize; j++) {
if (str[j] == '<')
count2++;
}
for (m = 0; m<fsize - 1; m++) {
if (str[m] == '=' && str[m + 1] == '=')
count3++;
}
for (n = 0; n<fsize - 4; n++) {
if (str[n] == 'e' && str[n + 1] == 'l' && str[n + 2] == 's' && str[n + 3] == 'e')
count4++;
}
for (l = 0; l<fsize - 2; l++) {
if (str[l] == 'i' && str[l + 1] == 'f')
count5++;
}
int br;
br = count4 + count5;
printf("\nOccurence of character '%c' : %d", '>', count1);
printf("\nOccurence of character '%c' : %d", '<', count2);
printf("\nOccurence of character == : %d ", count3);
printf("\nOccurence of character else : %d ", count4);
printf("\nOccurence of character if: %d \n", count5);
printf("\nobsht broi if+else: %d ", br);
fclose(fp);
return 0;
}
At any point of time if u need any assistance please ping me :) Thank you.

Related

How to ignore the ctrl+z, when checking the most common letter in a file (not case sensitive)

The function needs to find the most common character in a file and also get the data from the user. I used ctrl+z to terminate.
The problem is when I enter big character like: A + ctrl+Z, then it counts the Z as the most common one.
(If there is the same amount of character, it will return the biggest alphabetically. Empty file will return '\0').
char commonestLetter(){
char ch;
int count[26] = {0}, max = 0, index, i;
FILE* f = fopen("input.txt","w");
if (f == NULL){
printf("Failed to open the file \n");
return;
}
printf("Please enter the characters one by one, followed by enter\n");
printf("Ctrl + z and enter to finish\n");
while((ch = getchar()) != EOF){
fprintf(f,"%c",ch);
_flushall();
if (isalpha(ch))
count[ch - 'a']++;
}
fseek(f, 0, SEEK_END);
if (ftell(f) == 0){
ch = '\0';
return ch;
}
for (i = 0; i < 26; i++){
if (count[i] >= max){
max = count[i];
index = i;
}
}
fclose(f);
return index + 'A';
}
int main(){
char ch;
ch = commonestLetter();
if(ch)
printf("The commonest letter is %c", ch);
else
printf("No letters in the file");
printf("\n");
system("pause");
return 0;
}
You declared that the function should find the most common letter IN A FILE, but you read letters from stdin.
To get the most common letter ignoring case, you have to use letter-elevating function like tolower().
Try this:
#include <stdio.h>
#include <ctype.h>
char commonestLetter(char *file_name)
{
char ch, max_char = '\0';
int count[26] = {0}, max_count = 0;
FILE *f = fopen(file_name, "r");
if (f == NULL) {
printf("Failed to open the file %s\n", file_name);
return '\0';
}
while (fread(&ch, 1, 1, f) > 0) {
if (isalpha(ch) &&
(++count[tolower(ch) - 'a']) > max_count)
max_char = ch;
}
fclose(f);
return max_char;
}
int main(int argv, char *argc[])
{
char ch;
if (argv < 2) {
printf("Usage: %s filename\n", argc[0]);
exit();
}
ch = commonestLetter(argc[1]);
if(ch)
printf("The commonest letter in the file %s is '%c'\n",
argc[1], ch);
else
printf("No letters in the file %s\n", argc[1]);
return 0;
}

C: Occurrence of Letters in Text file

Program takes an input file through the command line and outputs the occurrence of each letter in the text file. Not sure where I went wrong.
int main(int argc, char *argv[]) {
char word[1000];
int a = 0;
int b = 0;
int d = 0;
int c = 0;
int e = 0;
int f = 0;
int g = 0;
int h = 0;
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int n = 0;
int o = 0;
int p = 0;
int q = 0;
int r = 0;
int s = 0;
int t = 0;
int u = 0;
int v = 0;
int w = 0;
int x = 0;
int y = 0;
int z = 0;
int other = 0;
int counter, lenght;
FILE *fp = fopen(argv[1], "r");
fgets(word, 999, fp);
lenght = 1000;
for(counter = 0; counter < lenght; counter++) {
word[counter] = tolower(word[counter]);
if (word[counter] == 'a') {
a++;
}
else if (word[counter] == 'b') {
b++;
}
else if (word[counter] == 'c') {
c++;
}
else if (word[counter] == 'd') {
d++;
}
else if (word[counter] == 'e') {
e++;
}
else if (word[counter] == 'f') {
f++;
}
else if (word[counter] == 'g') {
g++;
}
else if (word[counter] == 'h') {
h++;
}
else if (word[counter] == 'i') {
i++;
}
else if (word[counter] == 'j') {
j++;
}
else if (word[counter] == 'k') {
k++;
}
else if (word[counter] == 'l') {
l++;
}
else if (word[counter] == 'm') {
m++;
}
else if (word[counter] == 'n') {
n++;
}
else if (word[counter] == 'o') {
o++;
}
else if (word[counter] == 'p') {
p++;
}
else if (word[counter] == 'q') {
q++;
}
else if (word[counter] == 'r') {
r++;
}
else if (word[counter] == 's') {
s++;
}
else if (word[counter] == 't') {
t++;
}
else if (word[counter] == 'u') {
u++;
}
else if (word[counter] == 'v') {
v++;
}
else if (word[counter] == 'w') {
w++;
}
else if (word[counter] == 'x') {
x++;
}
else if (word[counter] == 'y') {
y++;
}
else if (word[counter] == 'z') {
z++;
}
else {
other++;
}
}
printf("\nCharacter frequency in %s", argv[1]);
printf("\nCharacter Count");
printf("\na \t\t %d", a);
printf("\nb \t\t %d", b);
printf("\nc \t\t %d", c);
printf("\nd \t\t %d", d);
printf("\ne \t\t %d", e);
printf("\nf \t\t %d", f);
printf("\ng \t\t %d", g);
printf("\nh \t\t %d", h);
printf("\ni \t\t %d", i);
printf("\nj \t\t %d", j);
printf("\nk \t\t %d", k);
printf("\nl \t\t %d", l);
printf("\nm \t\t %d", m);
printf("\nn \t\t %d", n);
printf("\no \t\t %d", o);
printf("\np \t\t %d", p);
printf("\nq \t\t %d", q);
printf("\nr \t\t %d", r);
printf("\ns \t\t %d", s);
printf("\nt \t\t %d", t);
printf("\nu \t\t %d", u);
printf("\nv \t\t %d", v);
printf("\nw \t\t %d", w);
printf("\nx \t\t %d", x);
printf("\ny \t\t %d", y);
printf("\nz \t\t %d", z);
fclose(fp);
return 0;
}
Should output in two columns one being the letter and the next being the number of times that letter occurs
There are problems in your code:
you do not include <stdio.h> nor <ctype.h>
you only read one line and you do not even check if that succeeds. You should write a loop like while (fgets(word, sizeof word, fp)) {
you check all characters in the word array: you should stop at the end of the line: lenght = strlen(word);
tolower() should not be given a char argument, because on platforms where char is signed, negative values invoke undefined behavior. You can cast the argument as (unsigned char) to avoid this: word[counter] = tolower((unsigned char)word[counter]);
More room for improvement:
lenght is misspelt, it should be length.
you should use an array of counters to avoid all these tests and all these explicit printf statements.
check the argument count and fopen() success
no need to read line by line, handle one byte at a time read with getc(). However, reading one large chunk at a time can be faster because it uses fewer tests and locks.
the printf statements should output the newline at the end rather than at the beginning.
Here is a corrected and simplified version:
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
int count[UCHAR_MAX + 1] = { 0 };
int other, total;
int c;
const char *s;
FILE *fp;
if (argc <= 1) {
fprintf(stderr, "missing input file\n");
return 1;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open input file %s\n", argv[1]);
return 1;
}
total = 0;
while ((c = getc(fp)) != EOF) {
count[tolower(c)] += 1;
total++;
}
printf("Character frequency in %s\n", argv[1]);
printf("Character Count\n");
other = total;
for (s = "abcdefghijklmnopqrstuvwxyz"; *s; s++) {
printf("%c:\t%9d\n", *s, count[(unsigned char)*s]);
other -= count[(unsigned char)*s];
}
printf("other:\t%9d\n", other);
fclose(fp);
return 0;
}
Reading the file by chunks instead of one byte at a time improves the speed dramatically with recent C libraries, because the support for multithreading has made the getc() macros inefficient. Using 64K buffers, the code below is fifty times faster (50X) for a 400MB file:
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#define BUFFER_SIZE 65536
int main(int argc, char *argv[]) {
unsigned char buffer[BUFFER_SIZE];
long count[UCHAR_MAX + 1] = { 0 };
long other;
size_t i, n;
const char *s;
FILE *fp;
if (argc <= 1) {
fprintf(stderr, "missing input file\n");
return 1;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open input file %s\n", argv[1]);
return 1;
}
while ((n = fread(buffer, 1, sizeof buffer, fp)) != 0) {
for (i = 0; i < n; i++) {
count[buffer[i]] += 1;
}
}
other = 0;
for (i = 0; i <= UCHAR_MAX; i++) {
if (isupper(i)) {
count[tolower(i)] += count[i];
} else {
if (!islower(i))
other += count[i];
}
}
printf("Character frequency in %s\n", argv[1]);
printf("Character Count\n");
for (s = "abcdefghijklmnopqrstuvwxyz"; *s; s++) {
printf("%c:\t%9ld\n", *s, count[(unsigned char)*s]);
}
printf("other:\t%9ld\n", other);
fclose(fp);
return 0;
}
Here's a quick implementation I wrote. It doesn't use fgets, but that is most definitely an option.
The flow of the program should be simple, but it is as follows:
Check for a proper argument count.
Declare the variables we'll need.
Declare the file pointer and attempt to open the file.
If the file doesn't open, we'll error out.
Read in every character from the file one at a time and store it into our variable c.
Using our ascii table, we'll alter the values to get them into the proper position in our array.
Print out all of our values.
Close the file.
#include <stdio.h>
int main(int argc, char **argv){
if (argc < 2){
printf("Not enough arguments!\n");
return -1;
}
int A[27] = {0}, c;
FILE *inFile = fopen(argv[1], "r");
if (inFile == NULL){
printf("The file \"%s\" could not be opened.\n", argv[1]);
return -2;
}
while((c = fgetc(inFile)) != EOF){
if ( c >= 'a' && c <= 'z' ){
/* C is a lowercase character */
c-='a';
A[c]++;
}
else if ( c >= 'A' && c <= 'Z' ){
/* C is an uppercase character */
c-='A';
A[c]++;
}
else if (c == '\n'){
/* we're not counting newlines */
continue;
}
else {
A[26]++;
}
}
/* Print out all the values except the "Other" count. */
for (c = 0; c < sizeof A / sizeof A[0] - 1; c++){
printf("%c: %d\n", c+'a', A[c]);
} printf("Other: %d\n", A[26]); //Print out "Other" count
/* Close our file */
fclose(inFile);
return 0;
}

ignoring # when reading from text file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following text file
#1234
5,4
#tfxc
01AAX
11AA1
#tfxc
11AA1
11111
And I want to ignore the # and the data behind it when reading from the text file and the 5,4 are the dimensions of the matrix which I am storing in a 2d array.
This is my code:
#include <stdio.h>
FILE *inp;
int main(void) {
int i, j;
int y = 0;
int x = 0;
char comma;
char arr = 0;
inp = fopen("App.txt", "r");
fscanf(inp, "%d", &x);
fscanf(inp, "%c", &comma);
fscanf(inp, "%d", &y);
char array[y][x];
for (i = 0; i < y; i++) {
for (j = 0; j < x; j++) {
fscanf(inp, "%c", &arr);
if ((arr == '1') || (arr == 'X') || (arr == '0') || (arr == 'A')) {
array[i][j] = arr;
} else {
j--;
}
printf("%c", arr);
}
}
}
How I can do this?
Use fgets() to read lines, check if the line should be ignored, else parse the line to initialize your matrix.
Here is an example:
#include <stdio.h>
int main(void) {
int c, i, j, k, x = 0, y = 0;
char line[1024];
FILE *inp;
inp = fopen("App.txt", "r");
if (inp == NULL) {
printf("cannot open App.txt\n");
exit(1);
}
while (fgets(line, sizeof line, fp)) {
if (line[0] == '#') continue;
if (sscanf(line, "%d,%d", &x, &y) == 2)
break;
printf("invalid line: %s", line);
exit(1);
}
char array[y][x];
for (i = 0; i < y;) {
if (!fgets(line, sizeof line, inp)) {
printf("missing matrix data at row %d\n", i);
break;
}
if (line[0] == '#')
continue;
for (j = k = 0; j < x && line[k] != '\0'; k++) {
c = line[k];
if (c == '1' || c == 'X' || c == '0' || c == 'A') {
array[i][j] = c;
j++;
putchar(c);
}
}
putchar('\n');
if (j != x) {
printf("missing matrix values at %d,%d\n", i, j);
}
i++;
}
fclose(inp);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int i, j;
int y = 0, x = 0;
FILE *inp = fopen("App.txt", "r");
if(!inp){
perror("fopen\n");
exit(EXIT_FAILURE);
}
while(2 != fscanf(inp, "%d,%d", &x, &y)){
int ch;
while((ch=fgetc(inp)) != '\n' && ch !=EOF);//skip
if(ch == EOF){
fprintf(stderr, "There is no dimension specified.\n");
exit(EXIT_FAILURE);
}
}
char array[y][x];
char format[32];
sprintf(format, "%%%d[01AX]%%c", x);
for (i = 0; i < y; i++) {
int status;
char newline = 0, buff[x+1];
status = fscanf(inp, format, buff, &newline);
if(status == 0 || status == 2 && newline != '\n'){//status 1 is OK
int ch;
while((ch=fgetc(inp)) != '\n' && ch !=EOF);//skip
--i;
continue;
}
if(status == EOF){
fprintf(stderr, "Necessary data is missing.\n");
exit(EXIT_FAILURE);
}
memcpy(array[i], buff, x);
}
fclose(inp);
//check print
for (i = 0; i < y; i++) {
for (j = 0; j < x; j++) {
putchar(array[i][j]);
}
putchar('\n');
}
return 0;
}

Occurring symbol per line

I want to get the occurrence of the symbol ';' for each line of this C program. I type the name of the file Source.c and try to count the occurring symbol, but i am getting the value for ALL of the ';' for each line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>/* For exit() function */
int main()
{
char file_name[150];
FILE *file2 = 0;
gets(file_name);
{
int rows = 1;//broq na vsichki redove
int dotcoma[150];
int j;
int c=0;
file2 = fopen(file_name, "r");//otvarq faial za chetene
if (file2 == NULL){
printf("Cannot open %s\n", file_name);
exit(2);
}//if
for (j = 0; j < 150; j++)
dotcoma[j]=0;
do{
c = fgetc(file2);
if (c == '\n') rows++;
if (';' == c)
dotcoma[rows-1] ++;
} while (c != EOF && rows <= 150);//chete do kraq na faila
if (ferror(file2)){
printf("Error reading file.\n");
}//if
printf("The number of the symbols on a row ");
printf("Row %d: %f\n", j + 1, (float)dotcoma[j]);
}
if (fclose(file2) == EOF){
printf("Cannot close %s\n", file_name);
}
_getche();
return 0;
}
You have almost everything in place. The only change you need to make is put the line
printf("Row %d: %f\n", j + 1, (float)dotcoma[j]);
in a for loop and change the format from %f to %d.
printf("The number of the symbols on a row \n");
for (j = 0; j < rows; j++)
{
printf("Row %d: %d\n", j + 1, dotcoma[j]);
}
You must make sure rows stays at 150 or below. Otherwise, you'll end up accessing the array dotcoma out of bounds. One way to do that would be to use:
do{
c = fgetc(file2);
if (c == '\n') rows++;
if (';' == c)
dotcoma[rows-1] ++;
} while (c != EOF && rows <= 150);//chete do kraq na faila
I have made great progress. It counts now for the frequency for every ';' for a line and wanted to add a new symbol frequency aswell '.' in my case, but it says that there is Stack arround varriable. Here it is the code working, but just without the second symbol frequency comma++ counter. Can someone give advice how to fix it ?
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS /* Да си изключа предупрежденията*/
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>/* For exit() function */
int main()
{
char file_name[1000];
FILE *file2 = 0;
gets(file_name);
int rows = 1;//broq na vsichki redove
int dotcoma[150];//broq na ;
int coma[150];//broq na .
int j;
char c;
file2 = fopen(file_name, "r");//otvarq faial za chetene
if (file2 == NULL){
printf("Cannot open %s\n", file_name);
exit(2);
}//if
for (j = 0; j<150; j++)
dotcoma[j] = 0;
coma[j] = 0;
do{
c = fgetc(file2);
if (c == '\n') rows++;
else{
if (c == ';')
dotcoma[rows - 1]++;
if (c == '.')
coma[rows-1]++;
}
} while (c != EOF);//chete do kraq na faila
if (ferror(file2)){
printf("Error reading file.\n");
exit(2);
}//if
printf("The number of the symbols on a row / the number of all symbols: ");
for (j = 0; j<rows; j++){
printf("Row %d: %f %f\n", j + 1, (float)dotcoma[j], coma[j]);
}
_getche();
if (fclose(file2) == EOF){
printf("Cannot close %s\n", file_name);
exit(2);
_getche();
return 0;
}
}

String Check not returning a value

Program should read in any input a user desires (in this case just a string of a’s and b’s) ended by an “*”, then it prompts the user for the substring they wish to search for (in this case “baab”). If the substring is found then the program indicates a yes, no if its not found. I was not allowed to use built in matching utilities and it has to read one character at a time.
I just replaced gets() with a scanf, now when i type in my substring and im sure its a match it still says no?
#include<stdio.h>
#include<string.h>
int search(char[], char[]);
int main()
{
char a[100], b[40];
int loc;
printf("Enter the main string :");
scanf("%s", a);
printf("Enter the search string :");
scanf("%s", b);
loc = search(a, b);
if (loc == -1)
printf("No");
else
printf("Yes %d", loc + 1);
return (0);
}
int search(char a[], char b[])
{
int i, j, firstOcc;
i = 0, j = 0;
while (a[i] != '*')
{
while (a[i] != b[0] && a[i] != '*')
i++;
if (a[i] == '*')
return (-1);
firstOcc = i;
while (a[i] == b[j] && a[i] != '*' && b[j] != '*')
{
i++;
j++;
}
if (b[j] == '*')
return (firstOcc);
if (a[i] == '*')
return (-1);
i = firstOcc + 1;
j = 0;
}
}
You need to terminate the second string with a * as well - then things match properly. As it is, your code keeps matching "one character too much" - and it finds the '\0' at the end of the b string which doesn't match.
If you don't want to have an asterisk at the end of your b string, you must not write code that expects it... You could modify your code as follows (I put in ample printf statements so you can see what is going on). Note - I left the fix to gets in as an exercise. Really, please. Fix it.
include <stdio.h>
int search(char a[], char b[]);
int main()
{
char a[100], b[40];
int loc;
printf("Enter the main string terminated with '*':");
gets(a); // please don't...
printf("Enter the search string :");
gets(b);
loc = search(a, b);
if (loc == -1)
printf("No");
else
printf("Yes %d", loc + 1);
return (0);
}
int search(char a[], char b[])
{
int i = 0, j = 0, lenB, firstOcc;
for(lenB=0; b[lenB]!='\0';lenB++);
printf("a is %s\n", a);
while (a[i] != '*')
{
printf("i = %d\n", i);
while (a[i] != b[0] && a[i] != '*')
i++;
if (a[i] == '*')
return (-1);
printf("matching a[i]=%c and b[0]=%c\n", a[i], b[0]);
firstOcc = i;
while (a[i] == b[j] && a[i] != '*' && j < lenB)
{
printf("a[%d] matches b[%d]\n", i, j);
i++;
j++;
}
if (j == lenB)
return (firstOcc);
if (a[i] == '*')
return (-1);
i = firstOcc + 1;
j = 0;
printf("going to take another look with i=%d and j=%d\n", i, j);
}
}

Resources