0

我下面的代码进行了一些字符串操作。我的问题是,如果没有输入节奏和/或文本,我想退出程序。换句话说,如果我按 ENTER(新行)并且没有为 scanf() 键入要读取的内容,那么程序必须完成。如您所见,我设置了一个条件,即当节奏不在范围 [2,6 ],程序结束。

int main()
{
   char text[80]; // To storage the text string 
   int rhythm; // To storage the rhythm value
   int k;
   banner();
   for( ; ; ){
        scanf("%i %79[^\n]", &rhythm, text);
        if(rhythm < 2 || rhythm > 6) break; // Termination of loop 
        printf("%s\n", text); // Printing original text
        conversion(text, rhythm); 
        printf("%s\n\n", text); // Printing modified text      
   }
   bye();     
   return 0;
}
4

3 回答 3

0

Try this

 if(rhythm < 2 || rhythm > 6 || text[0] == "\n") break;
于 2013-10-11T14:06:55.780 回答
0

不要scanf直接使用,如果用户想以 结尾,这不起作用Enter,我建议您阅读整行,分析它sscanf并使用这些函数的返回值:

 char buffer[255];

 for( ; ; ){
      if(!fgets(buffer,255,stdin))
         break;
      s=sscanf(buffer,"%i %79[^\n]", &rhythm, text);
      if (s!=2)
         break;
      // ...   
  }
于 2013-10-11T14:26:10.877 回答
-1

You should not use a for loop in this case :

do
{
   ...
}
while(rhythm >= 2 && rhythm <= 6);
于 2013-10-11T14:06:32.097 回答