添加int到字符串时遇到问题,尝试使用sprintf但我遇到了问题
问题描述:
我正在尝试读取文件并打印文件中的所有单词,忽略所有其他空格和符号。我有它与strcpy工作,但它给了我一个错误,我试图使用sprintf,但我真的不明白如何功能的话。它打印随机整数而不是字符串。添加int到字符串时遇到问题,尝试使用sprintf但我遇到了问题
编辑:我对C完全陌生,所以我没有把我的指针搞得太好。
FILE *file;
file = fopen("sample_dict.txt", "r");
int c;
int wordcount = 0;
int count = 0;
const char *a[10];
char word[100];
do {
c = fgetc(file);
//error statement
if (feof(file)) {
break;
}
if (isalpha(c) && count == 2) {
printf("%s\n", word);
memset(word, 0, sizeof(word));
count = 1;
wordcount++;
}
if (isalpha(c)) {
//strcat(word, &c);
sprintf(word, "%d", c);
continue;
}
count = 2;
continue;
} while (1);
fclose(file);
return (0);
return 0;
答
如果您需要字符,请在%C中使用%c作为格式说明符。如果您使用%d,它将起作用,但会显示为整数。
的另一件事是,如果你想用sprintf来连接一个字符的字符串,或和INT,你必须包括在sprintf的参数列表:
改变这一点:
sprintf(word, "%d", c);
要这样:
char newString[20];//adjust length as necessary
sprintf(newString, "%s%c",word, c);
在这里你的逻辑表明您只需要追加字符,如果是阿尔法即[az,AZ]
if(isalpha(c))
{
//strcat(word, &c);
sprintf(word, "%d", c);
continue;
}
将其更改为:`sprintf的(字, “%C”,C:
if(isalpha(c))
{
//strcat(word, &c);
char newString[20];//bigger if needed, 20 just for illustration here
sprintf(newString, "%s%d", word, c);
continue;
}
答
#define IN 1
#define OUT 0
FILE *file;
file = fopen("sample_dict.txt","r");
int c;
int wordcount = 0;
int status = OUT;//int count = 0;
//const char *a[10];//unused
char word[100] = "";
do {
c = fgetc(file);
if(feof(file)){
if(*word){//*word : word[0] != '\0'
printf("%s\n", word);
}
break;
}
if(isalpha(c)){
char onechar_string[2] = {0};//{c};
onechar_string[0] = c;
strcat(word, onechar_string);
if(status == OUT){
wordcount++;
}
status = IN;
} else {
if(status == IN){
printf("%s\n", word);
*word = 0;//memset(word,0,sizeof(word));
}
status = OUT;
}
}while(1);
fclose(file);
使用'%D'就可以打印它是这样的,当打印'char'为整);'但是你重置每个字符中的单词。更好地使用计数器并复制到数组中... – SHR 2014-10-09 23:54:05