From OP's comments, it sounds like the goal is to be able to read strings containing spaces. While there are ways to accomplish this using scanf()
, it would be better to use fgets()
, which is at the least less error-prone.
The fgets()
function can be used to read input for the number into a buffer, and this buffer can then be processed by sscanf()
to extract the number. Since fgets()
keeps the newline character, it is not left behind to interfere with the next I/O operation.
But, when fgets()
is used to get the string, since the newline is retained, it may be desirable to remove it. This can be accomplished in a number of ways, but here strcspn()
is used to provide the index of the first \r
or \n
character encountered; a \0
character is then written to this location, removing the terminating newline from the string.
The code below illustrates these suggestions. Note that both buffer[]
and string[]
are generously allocated to accommodate reasonably large inputs. If a user enters a large number of characters (more than 999 in this case), the extra characters are left behind in the input stream for the next I/O function call. Also note that the main loop has been streamlined a bit; now there is a for(;;)
loop that never terminates, broken out of when the user enters 0
for the number. And, there is a nested loop within the main loop that prompts the user to enter a number until a valid number is entered. Since the #include <stdlib.h>
was unnecessary, it was removed. Better code would check the values returned from the calls to fgets()
for possible errors.
#include<stdio.h>
#include<string.h>
int main(void)
{
int n = 1, cont;
char buffer[1000];
char string[1000];
for (;;) {
/* Loop until user enters a number */
do {
printf("Please enter a number: ");
fgets(buffer, sizeof buffer, stdin);
} while (sscanf(buffer, "%d", &n) != 1);
/* Break on 0 */
if (n == 0) break;
/* Get a string, and remove trailing newline */
printf("Please enter a string\n");
fgets(string, sizeof string, stdin);
string[strcspn(string, "\r\n")] = '\0';
cont = 0;
for (size_t i = 0; i < strlen(string); i++) {
if (string[i] == '.') {
cont++;
}
}
if (cont % 2 == 0){
printf("S\n");
} else {
printf("N\n");
}
}
return 0;
}