【问题标题】:Getting exact user input, c获取准确的用户输入,c
【发布时间】:2014-09-25 17:17:48
【问题描述】:

我一直在寻找解决方案,但没有找到任何解决方案,我一直在尝试制作一个用户输入大小的字符串,有什么办法可以做到这一点吗? (我试图消除 char 数组中的空值)。

编辑:对于丢失的信息,我深表歉意,编译器是 gcc -std=c99,操作系统是 Ubuntu。

这是我关注的主程序的一部分 + 标题(未完全完成),我正在尝试创建一个与用户输入长度相同且包含相同值的字符串.

编译器目前无法识别 myalloc 和 getline

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

int main() {
  char *string;
  int selection, bytes_read, nbytes = 255;
  unsigned char key, letter;

  do {
    ...
    printf("Enter a sentence:\n");
    string = (char *) myalloc(nbytes + 1);
    bytes_read = getline(&string, &nbytes, stdin);
    ...
  }while(..);
}  

【问题讨论】:

  • getline 可能是答案,但我觉得你的问题不清楚。您将用户输入的大小称为什么?从管道获取输入怎么样?
  • 我认为 getline 是在 POSIX 中定义的。您使用的是哪个操作系统/编译器?
  • 你的意思是如果用户输入42那么你想要一个长度为42的字符串并且没有一个字符应该是NUL? (希望第 42 次除外。您将需要 scanfmallocmemset。)或者您想要一个长度为 2 的字符串,该字符串读取为 "42"? (你需要getline 并且可能用\0 覆盖尾随的\n。)
  • @5gon12eder 我说的是一个长度为 2 的字符串,读取为“42”,更大的问题是如果 getline 可以使用,我必须使用 gcc 编译器和 idk。

标签: c string char


【解决方案1】:

将以下内容另存为main.c

#define _POSIX_C_SOURCE 200809L

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int
main()
{
  size_t n = 0;
  char * line = NULL;
  ssize_t count;
  printf("Enter a sentence: ");
  count = getline(&line, &n, stdin);
  if (count < 0)
    {
      perror("getline");
      return EXIT_FAILURE;
    }
  /* If it bothers you: get rid of the terminating '\n', if any. */
  if (line[count - 1] == '\n')
    line[count - 1] = '\0';
  printf("Your input was: '%s'\n", line);
  free(line);
  return EXIT_SUCCESS;
}

然后,在终端中:

$ gcc -o main main.c
$ ./main
Enter a sentence: the banana is yellow
Your input was: 'the banana is yellow'

还有一个更广泛的使用getline 的示例,包含在其man page 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2020-09-17
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多