简体   繁体   English

条件异常

[英]Strange behavior if condition

i am self taught programmer i face a problem here that if condition to enter only ( H OR T OR . ) doesn't get the string . 我是一个自学成才的程序员,我在这里面临一个问题,如果仅输入条件(H OR T OR。)无法得到字符串。 go to the ( printf ("Enter valid characters please \\n"); ) 转到( printf ("Enter valid characters please \\n");

below is my code : 下面是我的代码:

int i = 0 ;
int L ;

printf ("Please enter the lenght of report \n"); 
scanf ("%d" , &L);

if ( L>=1 && L<=500 )
{
        printf ("Please enter the Reoprt \n");
        string P = get_string ();
        if (P[i] !='H' && P[i] != 'T' && P[i] != '.')
        {
                printf ("Enter valid characters please  \n");
        }
        else 
        {
                printf ("GOOD3 \n");
        }
}
else 
{
        printf ("Please enter valid Length \n"); 
}

The reason you're having this problem is because scanf("%d", &L) will fetch one or more digits from the input and nothing else . 您遇到此问题的原因是, scanf("%d", &L)将从输入中获取一个或多个数字, 而不会获取其他任何内容 As a result, it will leave behind the newline character that you entered after typing in your number. 结果,它将在您输入数字后留下您输入的换行符。

When you call get_string() (I assume this is the same as GetString() in the CS50 library?), the first character it sees is this residual newline character, so all you're getting back is an empty string. 当您调用get_string() (我假设这与CS50库中的GetString()相同吗?),它看到的第一个字符是该残留的换行符,因此您得到的只是一个空字符串。

You can fix this easily enough. 您可以轻松地解决此问题。 Just replace scanf ("%d" , &L); 只需替换scanf ("%d" , &L); with L = GetInt(); L = GetInt(); .

Or, alternatively, replace scanf ("%d" , &L); 或者,替换为scanf ("%d" , &L); with scanf ("%d%c" , &L, &newline); scanf ("%d%c" , &L, &newline); , with newline declared as a char variable at the top of your main() function. ,并在main()函数顶部将newline声明为char变量。 This will consume the line break that follows the number, so that GetString() won't treat it as an empty string. 这将消耗数字后的换行符,因此GetString()不会将其视为空字符串。 For more details on how scanf() works, type man scanf at the command line. 有关scanf()如何工作的更多详细信息,请在命令行中键入man scanf

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

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