我在打印时遇到问题.当我请求用户插入int它工作时,但是当试图将其切换到char输入时它变得棘手并且不会打印任何东西.
#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;
}
Run Code Online (Sandbox Code Playgroud)
这里的主要问题是,您传递scanf()的是未初始化指针的地址hh.scanf尝试将单词存储在该地址时调用未定义的行为.
你应该创建hh一个数组,char hh[8] = {0};并使用scanf()这种方式:
scanf("%7s", hh); // to avoid buffer overflow
Run Code Online (Sandbox Code Playgroud)
那说,
if(hh == pt[j])不是比较字符串的方法.你需要用来strcmp()做,然后写if (strcmp(hh, pt[j]) == 0).scanf()以验证输入是否已正确转换.