C Programming Help I have to read a file that acts as a user

C Programming Help!

I have to read a file that acts as a user input for my program, andI\'m trying to read a string of numbers from a file, and read them one by one in my program. For example, reading a string of 1\'s and 0\'s (101111111100). I want to get the string and parse each number into my program, but it\'s not doing that :(

Here is my program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
//Opens file
FILE *f;
int c;
f=fopen(\"test.txt\",\"r\");

while(input != 3){

printf(\"Error detection/correction: \ \");
printf(\"---------------------------\ \");
printf(\"1) Enter parameters \ \");
printf(\"2) Check Hamming code \ \");
printf(\"3) Exit \ \");
printf(\"Enter selection: \");
fscanf(f, \"%d\", &input); printf(\"%d\ \", input);

if(input == 1){

printf(\"\ Enter the maximum length: \");
fscanf(f, \"%d\", &length); printf(\"%d\ \", length);
ptr = (int*)malloc(length);
printf(\"Enter the parity (0=even, 1=odd): \");
fscanf(f, \"%d\", &parity); printf(\"%d\ \ \ \", parity);
}

if(input == 2){

printf(\"Enter the Hamming code: \");
//fscanf(f, \"%s\", str);
if( fscanf(f, \"%s\", ptr)!=NULL ) {
// puts(HammingOutput);
HammingCodeLength = strlen(ptr)-1;
printf(\"\ ******Test: %c\ \", ptr);
}

}

printf(\"\ \ *** Program Terminated Normally\ \");
free(ptr);
fclose(f);
return 0;
}

Test.txt file:

1
14
0
2
101111111100
3

Solution

We can use sscanf to extract formated data from a string. (It works just like scanf,
but reading the data from a string instead of from standard input)

int GetNumber(const char *str) {
while (!(*str >= \'0\' && *str <= \'9\') && (*str != \'-\') && (*str != \'+\')) str++;
int number;
if (sscanf(str, \"%d\", &number) == 1) {
return number;
}
// No int found
return -1;
}
  

//this method will parse the string data into the program and extract the numbers from them.
  

C Programming Help! I have to read a file that acts as a user input for my program, andI\'m trying to read a string of numbers from a file, and read them one by
C Programming Help! I have to read a file that acts as a user input for my program, andI\'m trying to read a string of numbers from a file, and read them one by

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site