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; }
'\n'"goes into the function", then that’s exactly whatscanf("%d"...reads only the number reads.) As it should be. So what exactly do you need? What is the problem ? - AnTscanfread the data after pressingEnter, "swallowing"\n, then parsed the entered data and placed it in the variablelen. - user194374