大家好,请帮我理解一下!
我有一个txt文件,我读了不同的值。我成功了,但我也有ASCII,即。 KS98B2
我正在尝试阅读它并将其存储在一个值中。你能看看我的代码吗?单词“KS98B2”应存储在变量“name”中。所以我把它作为char声明在main中。你同意吗? 在“asc”功能里面有一个putchar,它打印得很好,我查了一下,我收到了KS98B2。
但是,在asc函数中,printf给出的值为:84122658 并且在main printf中给出了值:24
是的,我把%d放在printf中,name是一个char,但是变量怎么可能不一样?我怎样才能使它工作?请帮我 !
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
FILE *file;
char ch;
int asc(char eow, bool *eof) {
int var = 0;
while((ch=fgetc(file))!=EOF) {
putchar(ch);
if ((ch >= 'A') && (ch <= 'Z')) {
var <<= 4;
var += (ch - 'A' + 65);
}
else if ((ch >= '0') && (ch <= '9')) {
var <<= 4;
var += (ch - '0');
} else if (ch == eow) {
return var;
} else {
puts("Incorrect syntax.\n");
}
}
putchar('\n');
printf("Var inside asc %d\n", var);
}
int main() {
char name;
bool eof = false;
if ((file = fopen("messages.txt", "r")) == NULL) {
puts("WRONG FILE\n");
return 1;
}
while(!feof(file)) {
name= asc('\n', &eof);
printf("Var main: %d\n", name);
}
fclose(file);
return 0;
}
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
FILE *file;
//char ch;//There is no need to be a global variable
int asc(char eow, bool *eof) {
int var = 0;
int ch;//Type in order to compare the EOF and value must be int
while((ch=fgetc(file))!=EOF) {
if(isupper(ch))
var = var * 36 + (ch - 'A' + 10);
else if(isdigit(ch))
var = var * 36 + (ch - '0');
else if (ch == eow)
return var;
else {
fprintf(stderr, "\nIncorrect syntax.\n");
}
}
*eof = true;
return var;
}
int main(void) {
int name;//It must be int to receive the value of int
bool eof = false;
if ((file = fopen("messages.txt", "r")) == NULL) {
puts("WRONG FILE\n");
return 1;
}
while(!feof(file)) {
name= asc('\n', &eof);
printf("Var main: %d\n", name);
}
fclose(file);
return 0;
}
void putdecimal(int name) {
int i=0;
int var = name;
int array[30];
int cnt = 0;
while(var){
array[cnt++] = var % 36;
var /= 36;
}
for(i = cnt-1; i>=0; i--){
if(array[i]<10)
putchar(array[i] + '0');
else
putchar(array[i] - 10 + 'A');
}
}
答案 1 :(得分:0)
将读取的字符存储到数组中的示例。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
FILE *file;
char *gasc(int size, char buff[size], char eow){
int i = 0, ch = 0;
while(i < size - 1 && (ch=fgetc(file))!=EOF && ch != eow){
if (isupper(ch) || isdigit(ch)){
buff[i++] = ch;
} else {
fprintf(stderr, "\nIncorrect syntax.\n");
}
}
buff[i] = '\0';
if(i == 0 && ch == EOF)
return NULL;
return buff;
}
int main(void) {
char name[20];
if ((file = fopen("messages.txt", "r")) == NULL) {
puts("WRONG FILE\n");
return 1;
}
//is_eof is no longer necessary to represent NULL return value of gasc instead of EOF.
while(gasc(sizeof(name), name, '\n') != NULL) {
printf("'%s'\n", name);
}
fclose(file);
return 0;
}