How to write one line in five variables in C?

The goal is this: the user enters five numbers separated by spaces. they can be 1 digit 2 digit and so on. Question: how to write these five numbers not in one char variable, but in five variables (five arrays). Example: user entered

1 423 3 53 6

Variable a = 1 , b = 423 , c = 3 , d = 53 , d = 6 , with each element of the array containing one number: b [0] = 4 , b [1] = 2

I am writing in C, a program without an interface (it looks like a command line).

Here is the code:

 int i, j, a1,a2,a3,a4; char inp[50], a1[5],a2[5],a3[5],a4[5],a5[5]; scanf("%s", &inp); for(i=0; inp[i]!=" ";i++){ a1[i]=inp[i]; } for(i=i; inp[i]!=" ";i++){ j=0; a2[j]=inp[i]; j++; } for(i=i; inp[i]!=" ";i++){ j=0; a3[i]=inp[i]; j++; } for(i=i; inp[i]!=" ";i++){ j=0; a4[i]=inp[i]; j++; } for(i=i; inp[i]!=" ";i++){ j=0; a5[i]=inp[i]; j++; } 
  • And what did you write? - LEQADA
  • @LEQADA, I think at first to read the entire line, then cognitively check it - checked space character or not, if there is a space, then go to the write to the next. variable, if not, then continue recording in the same - Nik
  • @LEQADA, added - Nik
  • 2
    If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • Um ... In this code, everything that’s possible is wrong ... I’m not even sure if it compiles, but if so, all the conditions of for'ov are false. Learn to distinguish strings from characters. - Qwertiy

1 answer 1

Do scanf("%d",<переменна>); five times scanf("%d",<переменна>); . If we want to count a number, then

 int result[5]; for(int i = 0;i<5;++i) scanf("%d", &result[i]); 

If we want to count as a string, then

 char result[5][5]; for(int i = 0;i<5;++i) scanf("%s", result[i]); 

I will add my answer

 const int COUNT_OF_VALUES = 5; char inp[50], values[COUNT_OF_VALUES][5]; const char separator[]=" "; //Символы-разделители строки char *pNumber = NULL; //Указатель для функции strtok gets(inp); //считает строку до символа новой строки pNumber=strtok(inp,separtor); int i = 0; while(pNumber) { strcpy(values[i],pNumber); i++; pNumber=strtok(0,separator); } 
  • need to enter 5 variables through spaces - Nik
  • @Nik, he, in my opinion, will read every number before the space - Umed
  • @Nik, yes, scanf reads up to the first separator, which can also be a space. - Umed
  • @Nik, I added my answer. Perhaps the second method will help you more. - Umed