【问题标题】:How to exit while loop when enter key pressed in c code?在c代码中按下输入键时如何退出while循环?
【发布时间】:2014-11-13 18:34:56
【问题描述】:
#include <stdio.h>
#include <math.h>
#include <string.h>

int main(void){

    char str[100];
    char final;
    int sum = 0;
    int i = 0;
    int reminder;

    printf("Enter an abitrarily long string, ending with carriage return > ");

    while(1){
        //get user input of string unless they enter key exit
        if((scanf("%[^\n]s", str)) != '\n'){ 
            for(i = 0; i < strlen(str) ; i++)  
            {
                sum += str[i];     
            }
            reminder = sum%64;         //sum of char then divide by 64 and remainder of sum
            reminder = reminder + 32;  // remainder + 32
            final = reminder;          //change the int to char
            printf("Check sum is %c\n", final); // output
            printf("Enter an abitrarily long string, ending with carriage return > ");
        }
        else
        break;
    }
    return 0;
}

问题是,如果我不使用 while 循环,程序可以正常工作,但是一旦你使用 while,它就会进入无限循环...我该如何更改此代码?我想一直询问字符串,直到用户按下回车键退出。否则它应该继续询问字符串。

【问题讨论】:

  • 希望你也想做同样的事情.....stackoverflow.com/questions/16621020/…
  • 您能否更好地解释您的问题。首先你说“输入一个以回车结尾的字符串......并继续询问字符串”,但你说你希望它在他们按 Enter 时退出。回车和回车一样。
  • 好吧..它是一个程序,可以让用户输入字符串,如 EX) "sadjksajkdjakdjkslajdklsajdksajsdlkajks" 每个字符都有自己的 ascii 代码,即数字。我们将所有每个字符都添加为整数,然后除以 64,得到余数。余数将被添加 32(DEC) 然后转换为 char 输出。并且它的while循环应该一直向用户询问字符串,直到用户按下“enter”。所以基本上enter是用来退出while循环的。

标签: c


【解决方案1】:

scanf 不返回字符值,这是您当前正在检查以终止循环的值。它返回从格式字符串中成功解析的项目总数。这显然不等于 '\n'。

您需要使用 strcmp 来检查您的 str 是否包含换行符。

【讨论】:

  • 怎么样??你能说得更具体点吗??
  • 查找 strcmp。这很简单。如果 str 正好等于换行符,strcmp("\n", str) 将返回 0。
  • 您也可以通过索引 str 来直接进行字符比较。如果 str 中的第一个字符等于换行符, (str[0] == '\n') 将返回 true。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2021-03-02
  • 1970-01-01
  • 2016-05-08
  • 2014-04-12
  • 2011-11-07
  • 1970-01-01
相关资源
最近更新 更多