我在打印此内容时遇到问题。当我请求用户插入 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;
}
最佳答案
这里的主要问题是,您正在传递 scanf()
未初始化指针 hh
的地址。 scanf
调用未定义的行为,尝试将单词存储在该地址。
您应该将 hh
设为一个数组,例如 char hh[8] = {0};
并按如下方式使用 scanf()
:
scanf("%7s", hh); // to avoid buffer overflow
也就是说,
if(hh == pt[j])
不是比较字符串的方法。您需要使用strcmp()
为此,请编写if (strcmp(hh, pt[j]) == 0)
。- 您还应该检查
scanf()
的返回值,以验证输入是否已正确转换。
关于c - 在分隔符处分割一行文本后打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38769492/