【发布时间】:2018-08-02 19:14:44
【问题描述】:
int main() {
char userInput[100]; //Store user input
//Take user input
//scanf(" %s",&userInput);
//scanf("%[^\n]s",&userInput);
//scanf("%[^\n]", &userInput);
//gets(userInput);
scanf("%[]s", &userInput); //This takes input but doesnt leave input loop
printf(" %s",userInput);
//i = index to start for looping through the string, starting at the beginning
//count = Stores occurrences of '$'
//inputLength = length of the input, used for limit of loop
int i =0,count =0;
int inputLength = strlen(userInput);
//Loop through the user input, if the character is '$', the integer count will be incremented
for (i; i < inputLength; i++){
if (userInput[i] == '$'){
count++;
}
}
printf("%d", count);
return 0;
}
您好,我的代码有一些问题,我需要输入 3 行并计算输入中“$”的数量。未注释的输入法 "scanf("%[]s", &userInput);" 是我发现的唯一一种可以输入所有 3 行输入的方法,但我无法打破输入循环并继续我的程序。
任何帮助将不胜感激
【问题讨论】:
-
什么输入循环?
-
不要使用scanf。
-
你最好只使用
fgets一次读取一行,并保持$的运行总数 -
如果您的目标是确定前 3 行中
$的数量,则一次读取一个字符。数一下$和\n。当你读到第三个\n时,停下来。 -
是的,@Tom,
scanf真是让人头疼。它很强大,但它有很多陷阱并且经常绊倒人们。陷阱之一是,如果您不小心,它很容易产生缓冲区溢出。你不小心。