gpt4 book ai didi

objective-c - 我的程序中的输入语句被忽略

转载 作者:行者123 更新时间:2023-11-30 15:45:52 29 4
gpt4 key购买 nike

我是 Objective C 的初学者,所以请不要使用太复杂的单词。我正在编写一个删除某些字符(元音、辅音、标点符号等)的程序,但是当我尝试让用户输入自己的语句时,编译器只是忽略我的 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;
}

最佳答案

问题是 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,因此您应该检查在您的代码中满足该条件。)

关于objective-c - 我的程序中的输入语句被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18768254/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com