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;
}
Related
I am trying to read a text file, character by character, with fgetc() function but it does not show any output. It is a school project and it is still in very very simple way just to test the functionality of the program.
#include <stdio.h>
#include <stdlib.h>
void fn1(FILE *f);
void fn9(FILE *fp, char, char);
int main() {
FILE *fp = fopen("text.txt", "r");
if (fp == NULL) {
perror("Error: ");
exit(1);
}
fn1(fp);
fn9(fp, '0', '9');
fclose(fp);
return 0;
}
void fn1(FILE *f) {
int num, sum = 0, count = 0;
while (fscanf(f, "%d", &num) == 1) {
if (num > 0) {
sum += num;
count++;
}
}
printf("the avg of positive nums is %.2f", (float) sum / count);
}
void fn9(FILE *fp, char m, char n) {
int ch;
int count1 = 0, count2 = 0;
while ((ch = fgetc(fp)) != EOF) {
if (ch == m)
count1++;
if (ch == n)
count2++;
printf("%c", ch);
if (ferror(fp))
break;
}
printf("\n%c is seen %d times", m, count1);
printf("\n%c is seen %d times", n, count2);
fclose(fp);
}
The file's content that I test is:
90
16
-34
100
After fn(fp) return, fp will point to the last location in the file. It needs to be reset to the start of file before fn9 is called. Use fseek to point fp to the start of file and it should work :)
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;
}
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.
I'm trying to figure out why I cannot delete elements from the dict array. Could somebody help me out? The function removeWord is working as it is supposed to when removing the last added word, but not when trying to remove some other word.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUMBER_OF_WORDS 11
int clear(){
while(getchar()^'\n');
return 0;
}
int numberOfWordsInDict(char **dict){
int i = 0;
int c1 = 0;
for (i = 0; i < MAX_NUMBER_OF_WORDS; ++i){
if (dict[i] != 0){
c1++;
}
}
return c1;
}
void addWord(char **dict, char *word){
int c1 = numberOfWordsInDict(dict);
char *word1;
if (c1 >= 0 && c1 < 10){
word1 = (char*) malloc(sizeof(char)*(strlen(word)+1));
dict[c1] = word1;
strncpy(dict[c1], word, strlen(word));
dict[c1][strlen(word)] = '\0';
} else if (c1 >= 10){
printf("Dictionary is already full!\n");
}
}
void printDict(char **dict){
int i = 0;
int c1 = numberOfWordsInDict(dict);
printf("Dictionary:\n");
if (c1 == 0){
printf("The dictionary is empty.\n");
} else if (c1 > 0 && c1 <= 10){
while (dict[i] != NULL){
printf("- %s\n", dict[i]);
i++;
}
}
}
void removeWord(char **dict, char *word){
int i = 0;
for (i = 0; i < MAX_NUMBER_OF_WORDS; i++){
if (strncmp(dict[i], word, strlen(word)+1) == 0){
dict[i] = 0;// can only delete the last element of dict properly.
break;
}
}
}
int main(){
char *dict[MAX_NUMBER_OF_WORDS] = {};
char word[1024] = {};
char command;
while(1){
printf("Command (a/p/r/q): ");
while(scanf("%s", &command) == 1){
break;
}
;
clear();
if (command == 'a'){ // add word
scanf("%[^\n]s", &word);
clear();
addWord(dict, word);
} else if (command == 'p'){ // print dict
printDict(dict);
} else if (command == 'r'){ // remove word
printf("Remove a word: ");
scanf("%[^\n]s", &word);
clear();
removeWord(dict, word);
} else if (command == 'q'){ // quit
break;
}
}
int i = 0;
for (i = 0; i < MAX_NUMBER_OF_WORDS; i++){
free(dict[i]);
}
return 0;
}
example input:
a
dog
a
cat
a
apple
case 1:
r
apple
p
// output =
Dictionary:
- dog
- cat
a
uniform
p
// output =
Dictionary:
- dog
- cat
- uniform
// works fine
case 2
r
cat
p
// output =
Dictionary:
- dog
a
book
p
// output =
Dictionary:
- dog
// doesn't work as expected
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUMBER_OF_WORDS 11
int clear(){
while(getchar()^'\n');
return 0;
}
int numberOfWordsInDict(char **dict){
int c1 = 0;
for(int i = 0; i < MAX_NUMBER_OF_WORDS; ++i){
if (dict[i] != 0){
c1++;
}
}
return c1;
}
int vacancy(char **dict){
for(int i = 0; i < MAX_NUMBER_OF_WORDS; ++i){
if (dict[i] == 0){
return i;
}
}
return -1;
}
void addWord(char **dict, char *word){
int c1 = vacancy(dict);//It is not possible to use the registration number as an additional index.
if (-1 != c1){
dict[c1] = malloc(strlen(word)+1);
strcpy(dict[c1], word);
} else {
printf("Dictionary is already full!\n");
}
}
void printDict(char **dict){
int c1 = numberOfWordsInDict(dict);
printf("Dictionary:\n");
if (c1 == 0){
printf("The dictionary is empty.\n");
} else {
for(int i = 0; i < MAX_NUMBER_OF_WORDS; ++i){
if(dict[i])
printf("- %s\n", dict[i]);
}
}
}
void removeWord(char **dict, char *word){
for(int i = 0; i < MAX_NUMBER_OF_WORDS; i++){
if (strcmp(dict[i], word) == 0){
free(dict[i]);//need free
dict[i] = 0;// can only delete the last element of dict properly.
break;
}
}
}
int main(){
char *dict[MAX_NUMBER_OF_WORDS] = { NULL };
char word[1024] = { 0 };//forbids empty initializer braces
char command;
while(1){
printf("Command (a/p/r/q): ");
scanf("%c", &command);//%s buffer over run
clear();
if (command == 'a'){ // add word
scanf("%[^\n]", word);
clear();
addWord(dict, word);
} else if (command == 'p'){ // print dict
printDict(dict);
} else if (command == 'r'){ // remove word
printf("Remove a word: ");
scanf("%[^\n]", word);
clear();
removeWord(dict, word);
} else if (command == 'q'){ // quit
break;
}
}
int i = 0;
for (i = 0; i < MAX_NUMBER_OF_WORDS; i++){
free(dict[i]);
}
return 0;
}
Inside printDict() use
while (i<MAX_NUMBER_OF_WORDS){
if(dict[i] != 0)
printf("- %s\n", dict[i]);
i++;
}
instead of
while (dict[i] != NULL){
printf("- %s\n", dict[i]);
i++;
}
because even if you know if there are c1 number of words, you don't know their location as in where those c1 words are present.
Also change
while(scanf("%s", &command) == 1)
to
while(scanf("%c", &command) == 1)
since command is of char type.
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;
}