我是Objective C的初学者,所以请不要高句话。
我正在做一个程序,删除某些字符(元音,辅音,punct等),但当我试图让用户输入自己的语句时,编译器只是忽略我的fgets
(语句),它忽略了我的while循环条件第二次。问题是在第81-87行(允许用户输入他们想要删除的字符)和第98行(while循环输入语句。再次我不是专业人士,只知道一些基础知识。抱歉格式不正确。我不太了解stackoverflow
#import <Foundation/Foundation.h>
#define max 100
//characters is the character that the function is going to check for
NSCharacterSet *isChar(NSString * characters)
{
NSCharacterSet * theChar=[NSCharacterSet characterSetWithCharactersInString:characters];
return theChar;
}
NSString *removeChar(NSString * myInput , NSString * characters)
{
NSString * name;
name=[NSMutableString stringWithString:myInput];
name = [[name componentsSeparatedByCharactersInSet: isChar(characters)] componentsJoinedByString: @""];
return name;
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
char myString[max];
char tempWord[max];
NSInteger length =0;
NSInteger otherlength=0;
NSString * NewString;
NSString * characters;
NSString * myInput;
int k = 0;
char l=('y');
NSLog(@"Enter a String");
fgets(myString, max, stdin);
length=strlen(myString);
myString [length - 1] = 0;
myInput= [[NSString alloc] initWithUTF8String:myString];
while (l=='y')
{
NSLog(@"What would you like to do?");
NSLog(@"1:Remove Vowels");
NSLog(@"2:Remove Punctuation");
NSLog(@"3:Remove Constanants");
NSLog(@"4:Remove Digits");
NSLog(@"5:Remove whatever you want");
scanf("%d",&k);
if (k==1)
{
characters=@"aAeEiIoOuU";
}
if (k==2)
{
characters=@"!@#$%^&*()+_-|}]{[';:/?.>,<";
}
if(k==3)
{
characters=@"qQwWrRtTyYpPsSdDfFgGhHjJlLzZxXcCvVbBnNmM";
}
if (k==4)
{
characters= @"1234567890";
}
if (k==5)
{//My problem starts here
NSLog(@"Enter a String");
fgets(tempWord, max, stdin);
otherlength=strlen(tempWord);
tempWord [length - 1] = 0;
characters= [[NSString alloc] initWithUTF8String:tempWord];
}
NSLog(@"Your orignal string is: %@ ", myInput);
NewString=removeChar(myInput,characters) ;
NSLog(@"Your new string is: %@", NewString);
NSLog(@"Do you want to continue?");
//The scanf works the first time but when it goes thru the loop the second time it
//it gets ignored
scanf("%c",&l);
}
NSLog(@"Take Care :)");
}
return 0;
}
答案 0 :(得分:1)
问题是scanf("%d",&k)
只读取数字,而不读取换行符
你在终端输入的。因此,下一个fgets()
只读取此换行符,而不是其他内容。
一种可能的解决方法是使用fgets()
代替scanf()
,因为它总是会读取
整行包括换行终止符,所以:
//scanf("%d",&k);
fgets(tempWord, sizeof(tempWord), stdin);
k = atoi(tempWord);
和
//scanf("%c",&l);
fgets(tempWord, sizeof(tempWord), stdin);
l = tempWord[0];
(请注意,如果没有读取任何内容,fgets()
将返回NULL
,因此您应该检查
对于你的代码中的那个条件。)