【问题标题】:getline(); in C don't stop input获取线();在C中不要停止输入
【发布时间】:2015-12-13 13:40:30
【问题描述】:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
     
char split_text(){

    int bytes_las;
    int antal_bytes = 40;
    char *min_strang;

    printf("Enter text: ");

    min_strang = (char *) malloc (antal_bytes + 1);
    bytes_las = getline (&min_strang, &antal_bytes, stdin);

    printf("\n%s",min_strang);

}

   
int main()
{
    printf("   MENU:\n");
    printf("1) Split text\n");
    printf("2) Upper case to lower case\n");
    printf("3) Lower case to upper case\n");
    printf("4) Remove character\n");
    printf("5) Add character\n");
    printf("6) Replace character\n");
    printf("7) Statistics\n");
    printf("8) Sort text\n");
    printf("0) Exit\n");
    
        
    int i;
    char option;

    for(i=0; i<5;i++){
                
        
        printf("I want: "); //assign the option number
        option = getchar();
        switch(option) {                //use function assigned to what option

        case '1'  :
                printf("do for 1\n");
            split_text();
                break;
    
        case '2'  :
                printf("do for 2\n");
            break;
    
        case '3'  :
                printf("do for 3\n");
            break;
    
        case '4'  :
                printf("do for 4\n");
            break;
    
        case '5'  :
                printf("do for 5\n");
            break;
    
        case '6'  :
                printf("do for 6\n");
            break;
    
        case '7'  :
                    printf("do for 7\n");
            break;
    
        case '8'  :
                printf("do for 8\n");
            break;
    
        case '0'  :
                printf("do for 0\n");
            exit(0);
    
        default :   
            break;
        }
        
    }
}

这是我在单独文件中的函数。调用它时,函数会读取并且我得到正确的“输入文本:”输出。但是,没有限制。当我按下 Enter 键时,什么也没有发生,只是继续输入。

我在 Ubuntu 上,只使用 C,没有编译错误。

【问题讨论】:

  • 您发布的代码看起来不错。请发布mcve。也许,你循环调用split_text()
  • 将读取的字符串返回给调用者在哪里?
  • @chqrlie 我认为没有回报。它应该在他完成后释放那个内存块。
  • @Michi:当然! OP 还应该测试bytes_las 以验证是否读取了输入。他没有给我们足够的背景来调查他的问题。
  • @Sroy 为我工作fine

标签: c input getline


【解决方案1】:

您可以通过多种方式结束输入,其中一种可能是:

ssize_t read;
read=getline(&min_strang, &antal_bytes, stdin);

if(read < 1){
    printf("Input ends here\n");
            return 1;  
    }

当没有更多可写时结束。

【讨论】:

  • "当没有更多可写的时候结束。"?它到底是如何结束的,从标准输入?
【解决方案2】:

问题是

        option = getchar();

由于输入通常是行缓冲的,因此您输入 e。 G。 1\n,我。 e.您将两个字符放在输入缓冲区中,其中您仅使用 1getchar(),而 \n 留在缓冲区中。此后调用 getline() 时,它会从缓冲区中获取下一个字符,并且此 \n 会立即导致 getline() 返回一个空行。
为了纠正这个问题,使用菜单输入直到\n,所以getline()必须读取新的输入:

        option = getchar(); if (option != '\n') while (getchar() != '\n') ;

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2020-07-30
    • 2021-11-27
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2019-10-31
    相关资源
    最近更新 更多