![](/img/trans.png)
[英]Why doesn't scanf with character set format read input in a for loop?
[英]scanf doesn't input space as a character
下面的程序應該從兩個輸入的字符之間的文件中打印出一行的所有字符。 它適用於所有測試用例,但明確輸入的字符之一是空格的情況除外。
恩。
輸入:
12345 Maja Majovska:54
15145 Aco Acoski:95
14785馬丁·馬丁諾斯基(Martin Martinoski):87
#
://在標簽下是空格
正確的輸出:
瑪雅·瑪約夫斯卡(Maja Majovska)
阿科·阿科斯基
馬丁·馬蒂諾斯基
我的輸出:
54
15145阿科·阿科斯基95
14785馬丁·馬蒂諾斯基87
#include<stdio.h>
#include<string.h>
void wtf() {
FILE *f = fopen("podatoci.txt", "w");
char c;
while((c = getchar()) != '#') {
fputc(c, f);
}
fclose(f);
}
int main()
{
wtf();
getchar();
char z1, z2, c;
FILE *f;
f=fopen("podatoci.txt", "r");
int flag=0;
scanf(" %c %c", &z1, &z2);
while((c=fgetc(f))!=EOF){
if(c==z1){
flag=1;
continue;
}
if(c==z2){
flag=0;
printf("\n");
}
if(flag)
printf("%c", c);
}
fclose(f);
return 0;
}
有人可以簡單地指出我在做什么錯嗎? 我是剛接觸文件的人。
我認為這段代碼應該工作。 同時輸入兩個字符#:(#是空格),然后按Enter
#include<stdio.h>
#include<string.h>
void wtf() {
FILE *f = fopen("podatoci.txt", "w");
char c;
while((c = getchar()) != '#') {
fputc(c, f);
}
fclose(f);
}
int main()
{
// wtf();
// getchar();
char z1, z2, c;
FILE *f;
f=fopen("podatoci.txt", "r");
int flag=0;
printf("enter chars : ");
// scanf(" %c %c", &z1, &z2);
// printf("chars are |%c| |%c|",z1,z2);
char name[3];
fgets(name, 3, stdin);
// printf("chars are |%c| |%c|",name[0],name[1]);
char buffer[512]; // I suppose 512 is enough (see Two problems below)
int i=0;
while((c=fgetc(f))!=EOF){
/* Different problems :
1 : you have a 'space' followed by 'end of line' before ':'
example you have a space before 54 but end of line before :
So you could not display characters when a 'space' is a found.
You have to use a temporary buffer
2 : you have to reset your flag at the end of line
3 : If you have ':' alone, do not printf("\n")
4 : If you have a 'space' after the first 'space', it must be printed
example : Maja Majovska
^ (this space)
*/
if(c=='\n') { // Address pb 2
flag=0;
i=0;
continue;
}
if(!flag&&c==name[0]){ // Address pb 4
flag=1;
continue;
}
if(flag&&c==name[1]){ // Address pb 3
flag=0;
buffer[i]='\0'; // end of string
printf("%s\n",buffer);
i=0;
}
if(flag)
buffer[i++]=c; // Address pb 1
}
fclose(f);
return 0;
}
一些說明:
大部分說明都在代碼注釋中(您可以在閱讀后將其刪除)
我使用fgets而不是scanf( https://stackoverflow.com/a/1248017/7462275 )
我這樣做是為了使代碼盡可能接近其原始形式。 但是,我認為最好逐行獲取文本並使用字符串函數(string.h)。 例如,要在兩個字符之間打印第一個子字符串(不執行健全性檢查:這兩個字符必須在字符串中)
while((fgets(buffer,512,f))!=NULL){
i=strchr(buffer,name[0]);
*(strchr(i,name[1]))='\0';
printf("%s\n",i);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.