Home > database >  Exception thrown in strings input output
Exception thrown in strings input output

Time:12-14

I had been having an issue with string in school project and couldn't manage to fix it, made a test program to troubleshoot but haven't had any luck. I'm trying to just make a simple program to take a string value and then print it to the console. When it tries to print the string the program crashes with an exception being thrown I don't understand I think it is trying to save the string data to a memory address it doesn't have access to but im not sure cuz I tried it on both my laptop and pc with the same issue.

"Exception thrown at 0x00007FFAACA60369 (ucrtbased.dll) in tokenizing.c.exe: 0xC0000005: Access violation writing location 0x0000001F1F100000."

#include <stdio.h>

int main() {
    char string[100];
    printf("Enter a string: ");
    scanf_s(" %s ", &string);
    printf(" %s ", string);

    return 0;
}

CodePudding user response:

scanf_s(" %s ", &string); fails as it is missing a parameter. %s obliges a pointer and size.

scanf_s(" %s ", string, (rsize_t) 100);

Review your compiler details on scanf_s() as the C standard is not followed in details by some compilers.


Alternative: Review fgets() to read a line into a string.


A space before "%s" serves no purpose. Best to drop it.

A space after "%s" blocks until following non-white-space detected. Best to drop this space too.

CodePudding user response:

in this code

#include <stdio.h>
int main() {
    char string[100];
    printf("Enter a string: ");
    scanf_s(" %s ", &string);
    printf(" %s ", string);

    return 0;
}

string is already a pointer, you do not need the & on it. The correct code is

#include <stdio.h>

int main() {
    char string[100];
    printf("Enter a string: ");
    scanf_s(" %s ", string);
    printf(" %s ", string);

    return 0;
}
  • Related