简体   繁体   English

使用fgets在C中获得一行

[英]Using fgets to get a line in C

I have this functions , but my fgets function doesn't work properly,can anyone help me ? 我有此功能,但我的fgets功能无法正常工作,有人可以帮助我吗? At case 3 , I ask the user to enter something he wants to search for the hotel, like a partial word, two words etc. po when i run it it doesn't work right , I dont understand why. 在第3种情况下,我要求用户输入他想搜索酒店的内容,例如部分单词,两个单词等。当我运行它时,它不能正常工作,我不明白为什么。

        scanf("%d", &option);


        case 3:
            printf("\nEnter the name of the hotel you want to search for.\n\n>>>");
            fgets(asked_hotel, sizeof(asked_hotel)-1, stdin);

            printf("The hotels matching what you searched are:\n\n");
            find_hotel(hotel_name,hotel_rating,address_name,city_name,address_code,NUM_HOTELS,asked_hotel);

The problem here is your use of scanf to get the option. 这里的问题是您使用scanf来获取选项。 It extracts the number, but leaves the newline in the buffer. 它提取数字,但将换行符留在缓冲区中。 This means that when you next call fgets it will read that newline and you will get an empty line. 这意味着当您下次调用fgets ,它将读取该换行符,并且您将获得一个空行。

The easiest solution is to ask scanf to skip trailing whitespace, including newlines. 最简单的解决方案是要求scanf跳过结尾的空格,包括换行符。 This is done by adding a space after the format code: 这是通过在格式代码后添加一个空格来完成的:

scanf("%d ", &option);
/*       ^         */
/*       |         */
/* Note space here */

Recommend changing all your scanf() calls to fgets() / sscanf() pairs. 建议将所有scanf()调用更改为fgets() / sscanf()对。 Example: 例:

scanf("%d", &option);

to

char buf[80];
fgets(buf, sizeof(buf), stdin);
sscanf(buf, "%d", &option);

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

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