简体   繁体   English

试图打破 fgets while 循环

[英]Trying to break out of fgets while loop

#include <stdio.h>
#include <string.h>

int main(){
    char c[20], result[50];
    int bool = 0, count = 0, i;
    
    while(fgets(c,20,stdin) != NULL){
        int stringSize = strlen(c);
        if(stringSize == 11){
            
            int ascii = (int)(c[i]);
            
            for(i = 0; i < stringSize; i++){
            
                if(ascii >= 'A' && ascii <= 'Z'){
                    bool = 1;
                }
            }
        }
    }
        if(bool == 1){
            count++;
            strcat(result,c);
        }
    
    printf("%d", count);
    printf("%s",result);
}

Good morning, I am fairly new to programming, and I've spent quite a while Googling and searching around for this issue already, but I can't seem to wrap my head about it.早上好,我对编程还很陌生,我已经花了很长时间在谷歌上搜索和搜索这个问题,但我似乎无法理解它。 Basically I'm trying to filter an fgets so that it reads each string, and if they're capital letters, they're "valid".基本上我试图过滤一个 fgets 以便它读取每个字符串,如果它们是大写字母,它们是“有效的”。 However, I can't even get the fgets to stop accepting more input.但是,我什至无法让 fgets 停止接受更多输入。

Edit: The idea is to store in result every String that has 10 capital letters, and for the fgets while loop to break once the user gives no input ('\0')编辑:想法是在结果中存储每个具有 10 个大写字母的字符串,并且一旦用户没有输入 ('\0'),fgets while 循环就会中断

If you are entering strings from the standard input stream then it is better to rewrite the condition of the while loop the following way如果您从标准输入 stream 输入字符串,那么最好通过以下方式重写 while 循环的条件

while( fgets(c,20,stdin) != NULL && c[0] != '\n' ){

In this case if the user just pressed the Enter key without entering a string then the loop stops its iterations.在这种情况下,如果用户只是按下 Enter 键而没有输入字符串,那么循环将停止其迭代。

Pay attention to that fgets can append the new line character '\n' to the entered string.注意 fgets 可以 append 换行符 '\n' 到输入的字符串。 You should remove it like你应该像这样删除它

c[ strcspn( c, "\n" ) ] = '\0';

Then you could write然后你可以写

size_t n = strlen( c );

if ( n == 10 )
{
    size_t i = 0;
    while ( i != n && 'A' <= c[i] && c[i] <= 'Z' ) ++i;

    bool = i == 10;
}

Pay attention to that it is a bad idea to use the name bool because such a name is introduced as a macro in the header <stdbool.h> .请注意,使用名称bool是一个坏主意,因为这样的名称是在 header <stdbool.h>中作为宏引入的。

Also it seems this if statement这似乎也是 if 语句

    if(bool == 1){
        count++;
        strcat(result,c);
    }

must be within the while loop.必须在 while 循环内。 And the array result must be initially initialized并且数组结果必须初始初始化

char c[20], result[50] = { '\0' };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM