扫描多个整数不知道整数的实际数 [英] Scan multiple integers without knowing the actual number of integers

查看:125
本文介绍了扫描多个整数不知道整数的实际数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要输入值的频率,我不知道...

I have to input values whose frequency i don't know...

例如第一个输入:1 32 54 65 6

For example first input: 1 32 54 65 6

第二个输入:2 4 5

second input: 2 4 5

我首先想到的是,扫描的值,如果新行的'\\ n'再破环,但没有那么好走,所以不是我说我使用的字符,然后我强制转换来获取数目,但这个问题也来了,它由一个扫描一个字符,如果它是一个负值它也是一个问题;

What i first thought was, scan the values, if new line '\n' then break the loop, but that didn't go so well, so instead i said i use characters, then i typecast to get the number but the problem with this also came that it scan one character by one and if its its a negative value its also a problem;

像这样

#include <stdio.h>

int main(){
int myarray[20];
int i=0, data;

while(1){
      scanf("%d", &data);
      if (data == '\n') break; 
      myarray[i]=data;
}

return 0;
}

但随后,scanf函数跳转所有的特殊字符,并查找仅整数...有没有扫描到整型数组的方式时,有它停止换行符?

but then, scanf jumps all the special characters and look for only ints... is there a way to scan ints to an array and when there is a newline it stops?

推荐答案

我的建议是,去为与fgets()


  1. 阅读全文从输入

  2. 标记化利用空间[ ] [或preferred分隔符] [使用的 的strtok() ]

  3. 分配内存来存储整数

  4. 将字符串输入到整数[也许 与strtol() ]并存储每个整数。

  1. Read the whole line from the input
  2. Tokenize using space [] [or your preferred delimiter] [using strtok()]
  3. Allocate memory to store the integer
  4. Convert the string input to integer [maybe strtol()] and store each integer.

另外,您可能要添加一些验证和错误检查。

Optionally, you may want to add some validation and error checking.

了解更多关于与fgets() 这里

另外,不要忘记摆脱尾随的 \\ n 与fgets()<存储在读缓冲器/ code>

这篇关于扫描多个整数不知道整数的实际数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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