扫描多个整数不知道整数的实际数 [英] Scan multiple integers without knowing the actual number of integers
问题描述
我要输入值的频率,我不知道...
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()
。
- Read the whole
line
from the input - Tokenize using space [
] [or your preferred delimiter] [using
strtok()
] - Allocate memory to store the integer
- 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屋!