How to get rid of seemingly random 0's generated by the strtol function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to get rid of seemingly random 0's generated by the strtol function?

I am dealing with this while loop below: while (fgets(binaryArray, MAX_COLUMNS, file)) { int index = 0, index2 = 0; while (binaryArray[index] != '\0'){ if (binaryArray[index] != ' ') { binaryArray[index2++] = binaryArray[index]; } index++; } binaryArray[index2]='\0'; //printf("%s", binaryArray); printf("%ld\n", strtol(binaryArray, NULL, 2)); } =========================================== When the printf("%s", binaryArray); is uncommented (and the printf("%ld\n", strtol(binaryArray, NULL, 2)); is commented out), I get desired binary numbers (without white space between the bits): 10101 10001 00011 10111 However, when the printf("%s", binaryArray); is commented out and the printf("%ld\n", strtol(binaryArray, NULL, 2)); is uncommented, I get the desired decimal values, but with unwanted 0's in between each print: 0 21 0 17 0 3 0 23 0 0 Could you explain why this is happening, and how I could prevent it from happening? ========================================== Entire code: https://code.sololearn.com/cPjtXK5U7u0V input text file has this: 4 5 1 0 1 0 1 1 0 0 0 1 0 0 0 1 1 1 0 1 1 1

5th Feb 2022, 7:13 AM
Solus
Solus - avatar
3 Answers
+ 2
First problem arises in printDecimalDigits. Add a '\n' to the scanf: void printDecimalDigits(char *fileName) { int fileNumRows; int fileNumColumns; char binaryArray[MAX_COLUMNS]; FILE *file = fopen(fileName, "r"); fscanf( file, "%d %d\n", &fileNumRows, &fileNumColumns ); Otherwise, the file pointer will point to that character, and that is what is messing up your output. Next, set MAX_COLUMNS to 11, otherwise fgets will not read the '\n' char again from the file. #define MAX_COLUMNS 11
5th Feb 2022, 8:15 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
@Ani Jona Better now, thank you. However, there's still a 0 at the end. I'll look into this a bit more.
5th Feb 2022, 8:46 AM
Solus
Solus - avatar
0
May be there is an empty row? I only wrote the file here in the playground from the info you provided. If so, then you may need to check for and skip empty lines.
5th Feb 2022, 8:53 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar