C program to read a file and print just the numbers - c

I have a file containing strings as well as numbers. Eg. my file Store-1.txt contains "coffee 2mug -4".
I need a c program to store the numbers only (i.e 2 and -4) by reading a file and saving just the numbers into an array.
i am not able to figure out how exactly to do this. Any suggestions please.
code is
#include <stdio.h>
int main(void)
{
char c,ch;
int flag=0;
FILE *fptr=fopen("Store-1.txt","r");
if(fptr)
{
while((c=fgetc(fptr))!=EOF)
{
if(c=='-' || c== '+')
{
ch=c;
flag=1;
}
if(c>='0' && c<='9')
{
if(flag == 1)
{
printf("%c",ch); flag =0;
}
printf("%c",c);
}
}
}
else
printf("Error : file not found");
system("pause");
}

read a file using fgetc() and printf() it if
c>='0' && c<='9'
Here is the full working code :
#include <stdio.h>
int main()
{
char c,ch;
int flag=0;
FILE *fp=fopen("file.txt","r");
if(fp)
{
while((c=fgetc(fp))!=EOF)
{
if(c=='-' || c== '+')
{
ch=c;
flag=1;
continue;
}
if(c>='0' && c<='9')
{
if(flag == 1)
{
printf("%c",ch); flag =0;
}
printf("%c",c);
}
else
flag=0;
}
}
else
printf("Error : file not found");
fclose(fp);}

#include <ctype.h>
#include <stdio.h>
int main(void)
{
int ch, n, sign;
sign = 1;
ch = getchar();
while (ch != EOF) {
if (ch == '-') {
sign = -1;
ch = getchar();
} else if (isdigit(ch)) {
n = 0;
do {
n = n * 10 + ch - '0';
ch = getchar();
} while (isdigit(ch));
n *= sign;
/*store n*/
} else {
sign = 1;
ch = getchar();
}
}
return 0;
}

Related

How can I verify if a file only contains numbers in C?

I'm a beginner in learning C. If I have a file with the given format:
12 20 40 60 80
04 10 34 30 20
How can I verify with a function that it's integers only.
I'm working on an assignment that requires me to do this. That is why I can't include my main but I am passing a file into my function.
bool check(FILE *fp) {
int numArray[26];
int i = 0;
int num;
while(fscanf(fp, "%d", &num)) {
if (isdigit(num) == 0) {
fprintf(stderr, "Not correct format ");
return false;
} else
{
numArray[i] = num;
i++;
}
}
}
If I give it the incorrect format such as
12x 10 15 13 10
Nothing happens. I was wondering if anyone can point me in the right direction?
fscanf will return the number of successfully recognized patterns from the format in the input; if it sees something that does not match the next format pattern (such as a letter for a %d pattern) it will reject it and return a smaller number. So in your case, you can just look for fscanf returning 0:
bool check(FILE *fp) {
int numArray[26];
int i = 0;
int num;
int matched;
while ((matched = fscanf(fp, "%d", &num)) != EOF) {
if (matched == 0) {
fprintf(stderr, "Not correct format\n");
return false;
} else if (i >= 26) {
fprintf(stderr, "Too many numbers\n");
return false;
} else
{
numArray[i] = num;
i++;
}
}
return true;
}
int is_number(char *str)
{
int i = 0;
while (str[i] != '\0')
{
if (str[i] < '0' || str[i] > '9')
return 0;
i++;
}
return 1;
}
maybe this. so you are looking if variable only has numbers?
ok maybe this works better
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
FILE *fp;
char c;
char s[100];
int i = 0;
fp = fopen("test.txt", "r");
if(fp == NULL)
{
printf("Error opening file");
exit(1);
}
while((c = fgetc(fp)) != EOF)
{
if(isdigit(c) == 0)
{
printf("Not only integers\n");
break;
}
}
if(c == EOF)
printf("Only integers\n");
fclose(fp);
return 0;
}
but yeah its pretty much same thing

C programm to read characters between two '*'

I want the programm to read the characters that are between two stars and if there are not two stars, it must print a respective message. For example if the input is 1abc*D2Efg_#!*34567, the output is between first tow stars (letters : 4, digits:1, other:3) any help will be appreciated
int main()
{
int ch,lowercase_lett,digits,other,uppercase_lett,asterisk;
lowercase_lett = 0;
uppercase_lett = 0;
digits = 0;
other = 0;
asterisk = 0;
printf("enter characters : ");
while((ch = getchar()) != '\n' && ch != EOF)
{
if(ch == '*')
{
asterisk++;
}
if(asterisk < 2)
{
printf("\ntwo asterisks not found\n");
}
else
{
if(ch>='a' && ch <= 'z')
{
lowercase_lett++;
}
else if(ch>='A' && ch <= 'Z')
{
uppercase_lett++;
}
else if(ch >='0' && ch <= '9')
{
digits++;
}
else
{
other++;
}
}
}
printf("\n%d letters %d digits and %d other" , lowercase_lett+uppercase_lett,digits,other);
return 0;
}
Count characters when exactly one asterisk has been found. Functions in ctype.h are useful to determine the type of characters.
#include <stdio.h>
#include <ctype.h>
int main(void){
int ch,lowercase_lett,digits,other,uppercase_lett,asterisk;
lowercase_lett = 0;
uppercase_lett = 0;
digits = 0;
other = 0;
asterisk = 0;
printf("enter characters : ");
while((ch = getchar()) != '\n' && ch != EOF)
{
if(ch == '*')
{
asterisk++;
if(asterisk>=2)
{
break;
}
}
else if(asterisk==1)
{
if(islower(ch))
{
lowercase_lett++;
}
else if(isupper(ch))
{
uppercase_lett++;
}else if(isdigit(ch)){
digits++;
}else{
other++;
}
}
}
if(asterisk<2)
{
printf("\ntwo asterisks not found\n");
}
else
{
printf("\n%d letters %d digits and %d other" , lowercase_lett+uppercase_lett,digits,other);
}
return 0;
}
You were almost there, but your code contains some lines in wrong places.
Look at my solution. I just tested and it works for your problem:
#include <stdio.h>
int main(){
int ch;
int lowercase_lett = 0;
int uppercase_lett = 0;
int digits = 0;
int other = 0;
int asterisks = 0;
printf("Enter characters: ");
while((ch = getchar()) != '\n' && ch != EOF)
{
if(asterisks == 2){
break; //End the search
}
else if(ch == '*'){
asterisks++; //Increment until we have 2 *
}
else if(asterisks == 1){
if((ch >= 'a') && (ch <= 'z')){
lowercase_lett++;
}
else if((ch >='A') && (ch <= 'Z')){
uppercase_lett++;
}
else if((ch >= '0') && (ch <= '9')){
digits++;
}
else{
other++;
}
}
}
if (asterisks >= 2){
printf("\n%d letters %d digits and %d other" , lowercase_lett+uppercase_lett,digits,other);
}
else{
printf("\ntwo asterisks not found\n");
}
return 0;
}

Find sum where user has to enter a command with parameters such as 'sum(par1, par2,...)'

User enters command with parameters.There are no errors, but I am having trouble with the weird output.
I took input as string, identified if the input matches the command 'sum', if it does then extracted the parameters in between sum[], stored them in an array and send them as arguments to sum function.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int sumOfArray(int arr[])
{
int sum=0;
for(int i=0;i++;i<sizeof(arr))
{
sum = sum + arr[i];
}
printf("%d\n",sum);
return sum;
}
int main()
{
char input[256];
int j=0,temp=0;
int arraySum[6]={0};
printf("user_account $> ");
fgets(input, sizeof(input), stdin);
if (input[0]=='s' && input[1]=='u' && input[2]=='m')
{
if (input[3]!='(')
{
printf("Please enter proper parameters : sum(num1, num2, ..)\n");
}
else
{
for (int i = 4; i++; input[i] < ']')
{
if (input[i] !=',')
{
if (!isdigit(input[i]))
{
printf("Please enter only digits\n");
break;
}
else
{
temp = int(input[i]);
printf("%d\n",temp);
arraySum[j] = arraySum[j]*10 + temp;
}
}
else j++;
}
}
sumOfArray(arraySum);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sumOfPara(void){
int v, sum = 0;
char ch;
while(1){
if(2 == fscanf(stdin, "%d %c", &v, &ch) && (ch == ',' || ch == ')')){
sum += v;
if(ch == ')')
break;
} else {
fprintf(stderr, "Parameter is invalid.\n");
exit(EXIT_FAILURE);
}
}
return sum;
}
int main(void){
char command[32];
char left_paren;
printf("user_account $> ");
if(2 != fscanf(stdin, "%31[a-z] %c", command, &left_paren) || strcmp(command, "sum") != 0 || left_paren != '('){
fprintf(stderr, "Please enter proper parameters : sum(num1, num2, ..)\n");
exit(EXIT_FAILURE);
} else { //rest
printf("%d\n", sumOfPara());
}
return 0;
}

Handling inputs for int, char, float

I am trying to write a program that loops asking the user to continuously input either a float, int, or char and echo it back to them until they enter 'q', then the loop ends. I do not understand how to decipher between an int, char, or float before entering the loop. I have tried if (scanf("%c", ch)) and so on for float and int and that works great, but once I added the loop in it's messing me up. I have tried several different combinations, but I have still not found my answer.
Here is one attempt to show you exactly what I am trying to do:
char ch;
int num = 0;
float fl = 0;
printf("Enter a value: ");
while(ch != 'q') {
if (scanf("%c", &ch) && !isdigit(ch)) {
printf("You entered a character %c\n", ch);
}
else if (scanf("%d", &num)) }
printf("You entered an integer %d\n", num);
}
else if (scanf("%d", &num)) {
printf("You entered a floating point number %f\n", fl);
}
printf("Enter another value: ");
}
}
This keeps doing something strange and I cannot pinpoint my problem. Thank you in advance!
You cannot accomplish that with your approach. You can scan a line and parse it accordingly:
char line[128]; /* Create a buffer to store the line */
char ch = 0;
int num;
float fl; /* Variables to store data in */
int r;
size_t n; /* For checking from `sscanf` */
/* A `do...while` loop is best for your case */
do {
printf("Enter a value: ");
if(fgets(line, sizeof(line), stdin) == NULL) /* If scanning a line failed */
{
fputs("`fgets` failed", stderr);
exit(1); /* Exits the program with a return value `1`; Requires `stdlib.h` */
}
line[strcspn(line, "\n")] = '\0'; /* Replace `\n` with `'\0'` */
r = sscanf(buffer, "%d%zn", &num, &n);
if(r == 1 && n == strlen(line)) { /* If true, entered data is an integer; `strlen` requires `string.h` */
printf("You entered an integer %d\n", num);
}
else{
r = sscanf(buffer, "%f%zn", &fl, &n);
if(r == 1 && n == strlen(line)) { /* If true, entered data is a float; `strlen` requires `string.h` */
printf("You entered a floating point number %f\n", fl);
}
else{
if(strlen(line) == 1) /* If true, entered data is a character; `strlen` requires `string.h` */
{
ch = line[0];
printf("You entered a character %c\n", ch);
}
else{ /* Entered data is something else */
printf("You entered \"%s\"\n", line);
}
}
}
}while(c != 'q');
Disclaimer: I wrote the above code using a mobile and I haven't tested it.
Update (did not test and wrote with my mobile):
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
int main(void)
{
int c = 0;
bool random = false;
bool flag = true;
bool is_float = false, is_char = false, is_number = false;
do{
c = getchar();
if(c == EOF)
break;
if(!random)
{
if(isdigit(c))
{
is_number = true;
}
else if(c == '.')
{
if(is_number)
{
if(is_float)
{
random = true;
}
else
{
is_float = true;
}
}
else if(!is_number && !is_float && !is_char)
{
is_float = true;
}
}
else if(c == '-' && !is_float && !is_number && !is_char);
else if(isalpha(c))
{
if(is_char)
random = true;
else
{
is_char = true;
if(c == 'q')
flag = false;
}
}
else
{
random = true;
}
if((is_char && is_float) || (is_char && is_number))
random = true;
if(c == '\n' && !is_char && !is_float && !is_number)
random = true;
}
if(c == '\n')
{
if(random)
/* puts("You entered a random string!"); */
puts("Invalid input!");
else if(is_float)
puts("You entered a float!");
else if(is_number)
puts("You entered a number!");
else if(is_char)
puts("You entered a character!");
else
puts("Error!");
if(!flag && !is_number && !is_float && !random)
flag = false;
else
flag = true;
is_char = is_float = is_number = random = false;
}
}while(flag);
puts("Done");
return 0;
}

How would i make this program loop the main twice?

I need my program to create two different text files (midinotes1 & midinotes2) and store two bits of data inside them to be read later on. is there an efficient way without copying the code? i understand i need to have filepointer1 writing to midinotes1 and filepointer2 writing to midinotes2 but i dont know how to make my program do that?
Thanks for any advice!
#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <math.h>
#include <string.h>
float mtof(int note, float frequency);
int main()
{
FILE *textFilePointer;
FILE *textFilePointer2;
int note;
int velocity;
int program;
int counter = 0;
char user;
float frequency;
do
{
printf("Press R to Record (R) or (X) to Exit: \n");
scanf(" %c", &user);
if (user == 'r' || user == 'R')
{
textFilePointer = fopen("/Users/Luke/Desktop/midinotes1.txt", "w");
counter = 0;
if (textFilePointer == NULL)
{
printf("Error Opening file.\n");
}
else
{
do
{
note = aserveGetNote();
velocity = aserveGetVelocity();
if (velocity > 0)
{
fprintf(textFilePointer, "%d\n, %d\n", note, velocity);
counter++;
}
program = aserveGetProgram();
} while (counter < 16);
fclose(textFilePointer);
}
}
else if(user == 'x' || user == 'X')
break;
} while(user != 'x' || user != 'X');
return 0;
}
float mtof(int note, float frequency)
{
frequency = 440.0 * pow(2, (note-69) / 12.0);
printf("%d\n", note);
return frequency;
}
int index = 0;
char filename[128];
do
{
printf("Press R to Record (R) or (X) to Exit: \n");
scanf(" %c", &user);
if (user == 'r' || user == 'R')
{
snprintf(filename, 120, "notes%d.txt", (index+1));
textFilePointer = fopen(filename, "w");
counter = 0;
if (textFilePointer == NULL)
{
printf("Error Opening file.\n");
}
else
{
do
{
// your work
} while (counter < 16);
fclose(textFilePointer);
index++;
}
}
else if(user == 'x' || user == 'X')
break;
} while(user != 'x' || user != 'X');
return 0;
int main()
{
FILE *textFilePointer;
char filename[100];
int note;
int velocity;
int program;
int counter = 0;
char user;
float frequency;
int sample = 0;
do
{
printf("Press R to Record (R) or (X) to Exit: \n");
scanf(" %c", &user);
if (user == 'r' || user == 'R')
{
sample++;
sprintf(filename, "/Users/Luke/Desktop/midinotes%d.txt", sample);
textFilePointer = fopen(filename, "w");
counter = 0;
if (textFilePointer == NULL)
printf("Error Opening file.\n");
else
{
do
{
note = aserveGetNote();
velocity = aserveGetVelocity();
if (velocity > 0)
{
fprintf(textFilePointer, "%d\n, %d\n", note, velocity);
counter++;
}
program = aserveGetProgram();
} while (counter < 16);
fclose(textFilePointer);
}
}
else if(user == 'x' || user == 'X')
break;
} while(user != 'x' || user != 'X');
return 0;
}

Resources