How to read numbers separated by space using scanf

时光怂恿深爱的人放手 提交于 2020-02-09 06:55:10

问题


I want to read numbers(integer type) separated by spaces using scanf() function. I have read the following:

  • C, reading multiple numbers from single input line (scanf?)
  • how to read scanf with spaces

It doesn't help me much.

How can I read numbers with space as delimiter. For e.g. I have following numbers as input 2 5 7 4 3 8 18 now I want to store these in different variables. Please help.


回答1:


I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.

scanf("%d %d %d", &var1, &var2, &var3);

Similarly if you want to read comma separated values use :

scanf("%d,%d,%d", &var1, &var2, &var3);



回答2:


Read as %s[^\n]

and then read each char of the string , and do a atoi() if it is a char , else ignore it.




回答3:


int main()
{
char string[200];
int g,a,i,G[20],A[20],met;

gets(string);
g=convert_input(G,string);

for(i=0;i<=g;i++)
    printf("\n%d>>%d",i,G[i]);
return 0;
}

int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
    temp=0;
    while(string[i]!=' ' && string[i]!='\0')
        temp=temp*10 + (string[i++]-'0') ;
    if(string[i]==' ')
        i++;
    K[j++]=temp;
}
return j-1;
}



回答4:


scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.

Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.




回答5:


It should be as simple as using a list of receiving variables:

scanf("%i %i %i", &var1, &var2, &var3);




回答6:


Here i just wrote a simple c code for adding two numbers and taking input from user. now a and b are inputs and %d % or %d%d doesn't matter, what you've to do that as soon as input asked just write first input then press spacebar then write 2nd input and so on.thing is even if u just put space between %d's then also no change will be change. hence, i think that best way is this nly.



来源:https://stackoverflow.com/questions/10425953/how-to-read-numbers-separated-by-space-using-scanf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!