I'm a programming noob so please bear with me.
I'm trying to read numbers from a text file into an array. The text file, "somenumbers.txt" simply holds 16 numbers as so "5623125698541159".
#include <stdio.h>
main()
{
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
for (i = 0; i < 16; i++)
{
fscanf(myFile, "%d", &numberArray[i]);
}
for (i = 0; i < 16; i++)
{
printf("Number is: %d\n\n", numberArray[i]);
}
}
The program doesn't work. It compiles but outputs:
Number is: -104204697
Number is: 0
Number is: 4200704
Number is: 2686672
Number is: 2686728
Number is: 2686916
Number is: 2004716757
Number is: 1321049414
Number is: -2
Number is: 2004619618
Number is: 2004966340
Number is: 4200704
Number is: 2686868
Number is: 4200798
Number is: 4200704
Number is: 8727656
Process returned 20 (0x14) execution time : 0.118 s
Press any key to continue.
change to
fscanf(myFile, "%1d", &numberArray[i]);
5623125698541159 is treated as a single number (out of range of int on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d specifier in your fscanf to %d,.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
for (i = 0; i < 16; i++)
{
fscanf(myFile, "%d", &numberArray[i]);
}
This is attempting to read the whole string, "5623125698541159" into &numArray[0]. You need spaces between the numbers:
5 6 2 3 ...
Loop with %c to read the stream character by character instead of %d.
There are two problems in your code:
the return value of scanf must be checked
the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)
The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.
The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):
#include <stdio.h>
int main(int argc, char *argv[]) {
int i, j;
short unsigned digitArray[16];
i = 0;
while (
i != sizeof(digitArray) / sizeof(digitArray[0])
&& 1 == scanf("%1hu", digitArray + i)
) {
i++;
}
for (j = 0; j != i; j++) {
printf("%hu\n", digitArray[j]);
}
return 0;
}
enter your file input like this
ex:
12
13
22
45
(after every number hit enter)
then run your programm it will run properly
Related
It seems like I didn't quite understand how the file stream works. My text file right now contains the following integers: 1 10 5 4 2 3 -6, but I would like the program to be able to read any number of integers from the file, should it change.
Apparently I'm not even using the correct functions.
The code I have written is the following:
int main() {
printf("This program stores numbers from numeri.txt into an array.\n\n");
int a[100];
int num;
int count = 0;
FILE* numeri = fopen("numeri.txt", "r");
while (!feof(numeri)) {
num = getw(numeri);
a[count] = num;
if (fgetc(numeri) != ' ')
count++;
}
int i;
for (i = 0; i < count; i++) { printf("%d ", a[i]); }
return 0;
}
I would like it to print out the array with the stored numbers, but all I get is: 540287029 757084960 -1
Can someone help me understand what I did wrong and maybe tell me how to write this kind of code properly?
I have fixed your code based on comments. I used fscanf to read from file and limited the amount of numbers that can be stored in array by checking count < 100 and checking whether fscanf filled exactly one argument.
Also, I checked that whether file could be opened or not, just for safety. If it couldn't be opened, then just print error message and return 1.
int main() {
printf("This program stores numbers from numeri.txt into an array.\n\n");
int a[100] = {0};
int num;
int count = 0;
int i = 0;
FILE* numeri = fopen("numeri.txt", "r");
if (numeri == NULL) {
printf("Can't open file\n");
return 1;
}
while (count < 100 && fscanf(numeri, "%d", &num) == 1) {
a[count++] = num;
}
for (i = 0; i < count; i++) { printf("%d ", a[i]); }
return 0;
}
My C Code is as so:
#include <stdio.h>
int main( int argc, char ** argv){
FILE *myFile;
myFile = fopen("numbers.txt", "r");
//read file into array
int numberArray[16];
for (int i = 0; i < 16; i++){
fscanf(myFile, "%1d", &numberArray[i]);
}
for (int i = 0; i < 16; i++){
printf("Number is: %d\n", numberArray[i]);
}
}
My numbers.txt file contains the follow values:
5
6
70
80
50
43
But for some reason my output
Number is: 5
Number is: 6
Number is: 7
Number is: 0
Number is: 8
Number is: 0
Number is: 5
Number is: 0
Number is: 4
Number is: 3
Number is: 0
Number is: 0
Number is: 4195904
Number is: 0
Number is: 4195520
Number is: 0
However I'm expecting it to print out numberArray to print out the identical contents of the text file. I'm not exactly sure why it's doing this, does anyone happen to know the reason? I'm aware that I'm making an array bigger than the amount of values that I can store, but I'm still confused as to why it can't store 70, 80, etc into one index?
It is because you are reading only 1 digit at a time.
Hence change the below.
fscanf(myFile, "%1d", &numberArray[i]);
to
fscanf(myFile, "%d", &numberArray[i]);
And your array should be of size number of integers in the file.
int numberArray[6];
for (int i = 0; i < 6; i++)
or
while (fscanf(myFile, "%d", &numberArray[i++]) == 1);
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *myFile = fopen("numbers.txt", "r"); // just init your variable directly
if (!myFile) { // Always check if there is no error
return EXIT_FAILURE; // handle it as you like
}
#define SIZE 16 // Avoid magic number
int numberArray[SIZE];
size_t n = 0; // n will represent the size of valid values inside the array
// Always check if scanf family has parsed your input also "%1d" ask to only parse
// one digit, so use %d if you want parse an integer
while (n < SIZE && fscanf(myFile, "%d", numberArray + n) == 1) {
n++;
}
for (size_t i = 0; i < n; i++) {
printf("Number is: %d\n", numberArray[i]);
}
}
I simply want to check whether a value which is present in a variable is integer or not.
My program below reads two values from "myfile.txt" and performs addition if and only if they are integers otherwise it returns "Invalid Output". I have successfully read values from "myfile.txt" but i have no way of checking whether the two values are integer or not.How to perform this test?
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *fp;
int i, mkji, num, num1, num2;
int s = 0;
int a[2];
char term, term2;
clrscr();
fp = fopen("myfile.txt", "r+");
if (fp != 0)
{
for(i = 0; i < 2; i++)
{
fscanf(fp, "%d", &a[i]);
}
for(i = 0; i < 2; i++)
{
printf("%d\n", a[i]);
}
num = a[0];
num1 = a[1];
num2 = num + num1;
printf("%d", num2);
mkji = fclose(fp);
}
else
printf("FILE CANNOT BE OPEN");
getch();
return 0;
}
Check the return value of fscanf. fscanf returns the number of succesfully scanned items or -1 if there was an IO error. Thus, if the number was malformed, fscanf("%d",&a[i]); should return 0.
Read the file as ASCII character and check for their ASCII Codes. If the ASCII lies in the range of a number 0 number has ASCII 48 and 9 number has ASCII 57. so each number lies between ASCII 48 to 57.
you can concatenate them in a string since you are reading characters until a space appears and once you get 2 numbers just add them :)
code can be in the form of
char[] number1;
char numRead;
keep reading the number using fscanf until a non-number appears.
if ( numRead >= '0' && num <= '9' ) // checking for if it is a number.
number1 += numRead; // atleast thats how you do it in C++
check the return value from fscanf()
it can return -1 for a non number
and 0 or 1 for a number.
I'm having an issue with this program.
What I'm trying to do is read lines from the file input.txt, where the first line is the number of integers in the file. input.txt is formatted
5 //num of ints
2
40
49
90
70
Then, I want to print to file output.txt so that output.txt is basically.
range 0-9 1
range 10-19 0
range 20-29 0
range 30-39 0
range 40-49 2
range 50-59 0
range 60-69 0
range 70-79 1
range 80-89 0
range 90-99 1
The ranges will only go up to 99. Thus there is only 10 ranges. So there will never be a number over 99 after the initial line in input.txt.
The issue I'm having is that the program works fine as long as the number of guesses is 10. I know this has to do with how I set the range numbers to increase, since it's tied to the loop. I'm lost on how to do it properly.
Any advice? Thanks, in advance!
What I've got so far:
/*
Print a numbers in range to file output.txt from the list of numbers in file input.txt
*/
#include <stdio.h>
int main(void)
{
FILE *input;
FILE *output;
int num_guesses, nums, bin_count=0, guesses_in_bin;
int i, j, k, firstline;
int Bin_Start = 0;
int bin[10];
input= fopen("input.txt", "r");
output= fopen("output.txt", "w");
fprintf(output, "Values Amounts\n");
fscanf(input, "%d", &num_guesses); //scans first line of input.txt for the number of guesses
for (j=0; j< (num_guesses); j++) //for number of guesses run inside loop
{
for (i=0; i< (num_guesses); i++)
{
fscanf(input, "%d", &nums);
//printf(" %d\n", nums);
if (nums >= Bin_Start && nums <= Bin_Start+9) //checks if number belongs in bin.
bin_count = bin_count+1;
}
//rewind
rewind(input);
fscanf(input, "%d", &firstline); // used to ignore first line of file
//reset bin count
numbers_in_bin = bin_count;
bin_count = 0;
fprintf(output, "%2d - %2d %d", Bin_Start, Bin_Start+9, numbers_in_bin);
fprintf(output, "\n");
//Update to next bin
Bin_Start = Bin_Start+10;
}
fclose(input);
fclose(output);
return 0;
}
Without even looking for more-or-less subtle bugs, stop right here, this solution is already wrong in its concept. The only sane way to solve this is create counters for all ten possible bins in advance like:
int bin[10] = { 0 };
then scan the file one time and do something as simple as
bin[input/10]++;
for output, loop over your bins, eg:
for (int i = 0; i < 10; ++i)
{
printf("%d-%d:\t%d\n", 10*i, 10*i+9, bin[i]);
}
I want to make a program which reads the text from a file and shows every character, the ASCI code of each one and the number of occurrences.
I wrote this but it doesn't show the occurrences.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE * pFile;
int i=0;
int j=0;
char text[j];
int ascii[256];
int occ[256];
int occurance=0;
int position;
pFile = fopen ("c:/1.in","r");
if (pFile==NULL) perror ("Error opening file");
else
{
while (!feof(pFile)) {
j++;
text[j]=getc (pFile);
ascii[j]= (int) text[j];
position=ascii[j];
occ[position]++;
}
for (i=1;i<j;i++){
occurance=position[i]
printf ("Chracter %c has ascii %d and occurs %d times \n", text[i],ascii[i],occ[occurance] );}
}
system("PAUSE");
return 0;
}
First, I don't see the point in this:
int j=0;
char text[j];
If you want to put every character in the file into an array then read the size of the file and malloc() the correct size to a pointer. But why do that anyway? If you're trying to count ever occurrence of ever character then just keep track of the possibilities.
For completeness you can use an array of 256 characters, but in reality if you're just looking at standard printable characters there should only be about 94.
This:
int main ()
{
int temp = 0, i;
int occ[256] = {0};
FILE * pFile = fopen("test.txt", "r");
if (pFile == NULL) perror("Error opening file");
else {
while (!feof(pFile)) {
temp = getc(pFile);
if((temp < 255) && (temp >= 0))
occ[temp]++;
}
}
//reads every character in the file and stores it in the array, then:
for(i = 0; i<sizeof(occ)/sizeof(int); i++){
if(occ[i] > 0)
printf(" Char %c (ASCII %#x) was seen %d times\n", i, i, occ[i]);
}
return 0;
}
will print every character, the ASCII code (in hex) and the number of times it showed.
An example input file of:
fdsafcesac3sea
yeilds an output of:
Char 3 (ASCII 0x33) was seen 1 times
Char a (ASCII 0x61) was seen 3 times
Char c (ASCII 0x63) was seen 2 times
Char d (ASCII 0x64) was seen 1 times
Char e (ASCII 0x65) was seen 2 times
Char f (ASCII 0x66) was seen 2 times
Char s (ASCII 0x73) was seen 3 times
Below simple logic works fine for me. Add file operations to get the buf.
int main()
{
char buf[] = "abcaabde";
char val[256] = {0};
int i = 0;
for (i = 0; i < sizeof(buf); i++)
{
val[buf[i]]++;
}
for (i = 0; i < 256; i++)
{
if (val[i] != 0)
{
printf("%c occured %d times\n", i, val[i]);
}
}
return 0;
}
Output is
occured 1 times
a occured 3 times
b occured 2 times
c occured 1 times
d occured 1 times
e occured 1 times