小编eri*_*415的帖子

功能fgets跳过用户输入?

当我使用该功能时fgets,程序会跳过用户输入,影响程序的其余部分.具有此效果的示例程序是:

#include <stdio.h>

int main() {
    char firstDigit[2];
    char secondDigit[2];

    printf("Enter your first digit: ");
    fgets(firstDigit, 1, stdin);
    printf("\nEnter your second digit: ");
    fgets(secondDigit, 1, stdin);
    printf("\n\nYour first digit is %s and your second digit is %s.\n", firstDigit, secondDigit);
}
Run Code Online (Sandbox Code Playgroud)

然后我想也许问题fgets可能是写新行,所以我改变了代码来解释:

#include <stdio.h>

int main() {
    char firstDigit[3];
    char secondDigit[3];

    printf("Enter your first digit: ");
    fgets(firstDigit, 2, stdin);
    printf("\nEnter your second digit: ");
    fgets(secondDigit, 2, stdin);
    printf("\n\nYour first digit is %c and your second digit is …
Run Code Online (Sandbox Code Playgroud)

c

5
推荐指数
1
解决办法
709
查看次数

何时使用包括警卫?

我知道在头文件中使用包含警戒是为了防止某些内容被定义两次.但是,使用此代码示例,完全没问题:

foo.c的

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

int main() {
    printf("%d", strlen("Test String"));
    somefunc("Some test string...");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

bar.h

#ifndef BAR_H_INCLUDED
#define BAR_H_INCLUDED
void somefunc(char str[]);
#endif
Run Code Online (Sandbox Code Playgroud)

bar.c

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

void somefunc(char str[]) {
    printf("Some string length function: %d", strlen(str));
}
Run Code Online (Sandbox Code Playgroud)

上面的代码片段是用编译的,gcc -Wall foo.c bar.c -o foo没有错误.然而,无论是<stdio.h><string.h>被列入没有包括后卫.将bar.h删除到单个语句时仍然没有错误void somefunc(char str[]);.为什么没有错误?

c macros include-guards header-files c-preprocessor

2
推荐指数
1
解决办法
1133
查看次数

`restrict` 关键字只能在函数定义中使用吗?

我想知道是否可以restrict只在函数定义中而不是在函数声明中包含关键字,如下所示:

void foo(char *bar);

void foo(char * restrict bar)
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)

由于foo只接受一个参数,因此任何指针别名都必须在foo. 调用函数的人不需要知道restrict修饰符。只在函数声明中省略关键字是否可以,就像 with 一样const

c keyword

1
推荐指数
1
解决办法
79
查看次数