Reputation: 45
We did this exercise in class today, but unfortunately, my code wasn't running properly. It won't print string1
. My teacher also could not figure out why this was happening.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char string1[20];
char string2[] = "It is almost end of semester!";
size_t idx;
int size;
printf("Enter string1:\n");
scanf_s("%s", string1);
size = sizeof(string2) / sizeof(char);
printf("\nString 1 is : %s\n\n", string1);
for (idx = 0; idx < size; idx++)
{
printf("%c ", string2[idx]);
}
puts("");
system("pause");;
}
Upvotes: 0
Views: 61
Reputation: 84642
You have used scanf_s
instead of scanf
which, as Mr. Lynch correctly pointed out requires an additional parameter. You can accomplish the same thing with scanf
itself. One approach is as follows:
#include <stdio.h>
#include <stdlib.h>
int main () {
char string1[20];
char string2[] = "It is almost end of semester!";
size_t idx;
int size;
printf ("Enter string1:\n");
scanf ("%[^\n]%*c", string1);
string[19] = 0; /* force null-termination of string1 */
size = sizeof (string2) / sizeof (char);
printf ("\nString 1 is : %s\n\n", string1);
for (idx = 0; idx < size; idx++) {
printf ("%c ", string2[idx]);
}
puts ("");
return 0;
}
output:
$ ./bin/strprn
Enter string1:
scanf_s is not scanf
String 1 is : scanf_s is not scanf
I t i s a l m o s t e n d o f s e m e s t e r !
Note: main()
is type int
not void
no matter what ms lets you get away with. It returns a value as well.
Upvotes: 0
Reputation: 81996
scanf_s
requires an extra parameter.
scanf_s("%s", string1, _countof(string1));
Upvotes: 1