c - 扫描 C 中的值直到遇到换行符, '\n'

标签 c arrays algorithm scanf getchar

如何scanf() 输入数组中的整数值,直到我按下回车键。

我相信我可以使用 getchar() != '\n'

但是我如何遍历该行?

假设我的输入是 20 21 2 12 2。我想要一个包含所有这些输入的数组。 我可以使用哪些给定函数来扫描它们。

最佳答案

  1. 您正在尝试将整数作为字符读取,因此一旦读取,您需要将其转换为整数。
  2. 使用 fgets() 将行读入缓冲区,然后解析输入缓冲区以获取整数。
  3. 将整数存储到数组中。

代码看起来像

char buf[300];
int a[5],i=0;
fgets(buf,sizeof(buf),stdin);
char *p = strtok(buf," ");
while(p != NULL)
{
  char *endptr;
  a[i] = strtol(p,&endptr,10);
  if ((*endptr != '\0') && (isspace(*endptr) == 0))
      printf("warning: invalid value detected\n");
  else
      i++;
  p = strtok(NULL," ");
}

您可以使用替代方法 strtol() 而不是 atoi() 将字符串转换为整数。

PS:您的buf 应该足够大以容纳整行。 fgets() 读取到换行符。

关于c - 扫描 C 中的值直到遇到换行符, '\n',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30692854/

相关文章:

c++ - pthread_exit(NULL);不工作

c - 返回包含该行从左到右学生高度的数组

c# - Streamreader 和 "Index was outside the bounds of the array"错误

algorithm - 通过矩形数组路由 "paths"

c++ - 如何获取拖入 Win32 应用程序的文件路径并将其删除?

html - 创建一个网页来演示 C 代码

c++ - 为什么第二个代码有效而第一个无效?

php - MySQLi Bind Param 与 IN 的数组

algorithm - 算出算法的下界?

algorithm - 使用搜索和排序的不相交集