In general, I need to enter the length of the string number. After entering the number and pressing enter, the carriage return ('\ n') goes to the function. So, how can I make scanf read only a number?

#include "stdio.h" #include "stdlib.h" char* GetLine(int len){ char* text = NULL; char ch; for(int counter = 1 ;; counter++){ ch = getchar(); text = (char*)realloc(text,counter*sizeof(char)); if((ch != '\n')&&(counter != (len+1))){ *(text+counter-1) = ch; } else{ *(text+counter-1) = '\0'; break; } } return text; } int main(){ // Disable stdout buffering setvbuf(stdout, NULL, _IONBF, 0); char* sep; sep = GetLine(-1); /*for(int i = 0; *(sep+i) != '\0'; i++){ printf("%c",*(sep+i)); }*/ // printf("\n"); int* len; len = (int*)malloc(sizeof(int)); printf("Введите длину текста:\n"); scanf("%d",len); printf("Длина текста: %d\n",*len); char* message; message = GetLine(*len); return 0; } 
  • Understood nothing. If '\n' "goes into the function", then that’s exactly what scanf("%d"... reads only the number reads.) As it should be. So what exactly do you need? What is the problem ? - AnT
  • A little incorrectly asked a question, I apologize. In general, how to make so that after entering the number we get rid of '\ n'? - ReCursia
  • @ReCursia You already got rid of. scanf read the data after pressing Enter , "swallowing" \n , then parsed the entered data and placed it in the variable len . - user194374

1 answer 1

You mean that '\n' remained in the buffer? Just read and ignore from the buffer everything up to '\n' inclusive - for example,

 scanf("%*[^\n]s%*c"); 

or you can use fgets(stdin) into some kind of buffer. Or cycle

 while(getchar() != '\n'); 

In this way, you delete everything that remains from the entered line, so if you type something like 45 18 and then you are going to count the second number, then you don’t need to do that :)