George Catalin
George Catalin

Reputation: 29

c scanf_s in visual studio 2017 don't work more than once

#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.

Upvotes: 2

Views: 1171

Answers (2)

user3629249
user3629249

Reputation: 16540

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.

Upvotes: 0

chux
chux

Reputation: 153407

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
  }  
}

Upvotes: 3

Related Questions