如何读取一个逗号和空格隔开的整数为C中的数组 [英] How to read integers separated by a comma and a white space into an array in C

查看:570
本文介绍了如何读取一个逗号和空格隔开的整数为C中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到输入的 INT1 INT2 ... INTN 。
我neeed这些整数的值存储在数组中。一个单独的函数用于获得要被读取的整数的数目。我怎样才能让这两个职能的工作?

I need a function that gets input in the form of int1, int2, ..., intn. I neeed to store the values of these integers in an array. A separate function is used to get the number of integers to be read. How can I make the two functions work?

如果现在还不清楚,这件事情是这样的:

If it's not clear, it's something like this:

功能1得到的整数以获得输入的数量被读取。那么函数2将读取输入的加上一个的,但输入必须是在一个单一的线,必须用逗号和/或空格分隔。

function1 gets an integer to get the number of input to be read. Then the function2 will read that input plus one but the input must be in a single line and must be separated by a comma and/or a white space.

FUNCTION1得到,例如 5 的。功能2将要读到这样输入: 3,21,5,1,5,2 的并存储到供以后使用一个单独的数组

Function1 gets, for example 5. function2 will want to read input like: 3, 21, 5, 1, 5, 2 and store it into a separate array for later use.

谁能帮助?谢谢。我想用循环的,但我记得,输入必须在一行。也许scanf函数?使用[^]但我怎么让它与第一个函数工作?

Can anyone help? Thanks. I thought of using loops but I remembered that the input must be in one line. Maybe scanf? With [^,]? But how do I make it work with the first function?

推荐答案

试试这个:

#include <stdio.h>

void getInput(int sizeOfInput, int arr[]) {
  int i = 0;
   printf("IN");
  for(; i < sizeOfInput - 1; ++i) {
    scanf("%d, ", &arr[i]);
  }
  scanf("%d", &arr[i]);
   printf("OUT");
}

main(){
  int sizeOfInput = 0;
  printf("Enter how many numbers do you want to enter?");
  scanf("%d", &sizeOfInput);

  int arr[sizeOfInput]; 
  getInput(sizeOfInput, arr);
}

对不起我懒,但你学习这将是最好弄清楚你使用它之前此code做什么,这也是一个原因,我没有发表评论吧。

Sorry I am lazy but for you to learn it would be the best to figure out what this code does before you use it, that is also a reason why I did not comment it.

这篇关于如何读取一个逗号和空格隔开的整数为C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆