#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
const int lung = 41;
void main() {
char ceva1[lung];
scanf_s("%[a-zA-Z ]s", ceva1, sizeof(ceva1));
printf("%s", ceva1);
scanf_s("%[a-zA-Z ]s", ceva1, sizeof(ceva1));
printf("%s", ceva1);
_getch();
}
Only the first printf_s work, it just printf twice the text. The single way that i found to work is in c++ with getline but i want to do it in c with scanf preferably.
Neither call to scanf_s("%[a-zA-Z ]s",
consumes the '\\n'
keyed in with Enter . '\\n'
remains as the next character to be read @Serge Ballesta . So the 2nd call reads nothing. Had code checked the return value of scanf_s()
, this may have been deduced.
Instead of scanf*
and *getc*
, read a line with fgets()
@user3121023 , and lop off the potential trailing '\\n'
if desired.
if (fgets(ceva1, sizeof ceva1, stdin)) {
ceva1[strcspn(ceva1,"\n")] = '\0';
// use ceva1
}
Avoid using scanf*()
anywhere, even for reading numbers.
char buf[80];
if (fgets(buf, sizeof buf, stdin)) {
int a,b;
if (sscanf(buf, "%d%d", &a, &b) == 2) {
// use a, b
}
}
this expression:
"%[a-zA-Z ]s"
should be:
"%[a-zA-Z ]"
Notice no trailing 's'`.
However, this will stop input at any character that is not alphabetic (like a space, or punctuation or newline or digit. )
If wanting to input everything on a line, use a format string like:
"%[^\n]"
If you post some sample input, we can be much more specific with our help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.