christian christian - 3 months ago 9
C Question

printing after splitting a line of text at delimiters

I am having trouble printing this. When I requested the user to insert an

int
it worked, but when attempting to switch it over to a
char
input it got screwy and won't print anything.

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

int main() {
const char delim[2] = ",";
char *token;
int j = 0;
char *hh;
FILE *ptr_file;
char buf[1000];

ptr_file = fopen("input.txt", "r");
if (!ptr_file)
return 1;

char *pt[] = { "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na" };

printf("what element do you want(Use atomic number)");
scanf("%s", &hh);

for (j = 0; j <= 3; j++) {
if (hh == pt[j]) {
fgets(buf, 1000, ptr_file);
token = strtok(buf, delim);
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, delim);
}
break;
} else {
fgets(buf, 1000, ptr_file);
continue;
}
}

fclose(ptr_file);
return 0;
}

Answer

The major problem here is, you are passing scanf() the address of an uninitialized pointer hh. scanf invokes undefined behavior trying to store the word at that address.

You should make hh an array, like char hh[8] = {0}; and use scanf() this way:

 scanf("%7s", hh);  // to avoid buffer overflow

That said,

  • if(hh == pt[j]) is not the way to compare strings. You need to use strcmp() to do that, and write if (strcmp(hh, pt[j]) == 0).
  • you should also check the return value of scanf() to verify if input was correctly converted.
Comments