简体   繁体   中英

C - If else scanf not working as expected

I'm new to coding in general, and very new to C.

I'm trying to write a program in c that asks the user for input and based on that users input, prints specific text to a .txt file. Please have a look at my code and let me know what I'm doing wrong.

Please have a look at my code below. Thanks very much for your assistance.

Matt

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


FILE * fptr; 

int main(){

char name[32];
char partNum[32];
char desc[250];
char ans1;
char ans2;
char sn[50];
char ansRep;

fptr = fopen("C:\\Users\\mgreene\\Documents\\EmailTemplates\\QCIssue.txt", "w");

if (fptr ==0)
{
printf("Error--file could not be opened\n");
exit(1);
}

printf("What is the customer's first name?\n");
scanf("%s", name);

printf("With which Part number is the user experiencing difficulties?\n");
printf("Enter Part Number:");
scanf("%s", partNum);

printf("Please enter a brief description of the problem\n");
scanf("\n%s", desc);

printf("Does the product have a serial number?\n");
scanf("%c", &ans1);

if (!strcmp(&ans1, "y")== 0)
{
printf ("Do you know the serial number?\n");
scanf("\n%c", &ans2);

if (!strcmp(&ans2, "y")==0)
{
printf ("Please enter the SN:\n");
scanf("\n%s", sn);

fprintf(fptr, "\nHi %s,\n\nI hope this message finds you well.\n\nI write to you today       as the Quality Manager at Blank. I received a report that you're experiencing difficulties with part: %s, %s; specifically, the report indicates that %s. Is that an accurate description of the problem? Firstly please accept my apologies on behalf of Blank for the difficulties you're experiencing with this part. As an ISO9001:2008 compliant organization, Blank takes all issues related to customer satisfaction very seriously. It is our intention to resolve this matter as soon as is possible.\n\n", name, partNum, sn, desc);
    }
    else 
    {
    fprintf(fptr, "\nHi %s,\n\nI hope this message finds you well.\n\nI write to you today as the Quality Manager at Blank. I received a report that you're experiencing difficulties with part: %s; specifically, the report indicates that %s. Is that an accurate description of the problem? Firstly please accept my apologies on behalf of Blank for the difficulties you're experiencing with this part. As an ISO9001:2008 compliant organization, Blank takes all issues related to customer satisfaction very seriously. It is our intention to resolve this matter as soon as is possible.\n\nBefore I can begin an investigation into this problem, I'll need the serial number from that unit. Can you please forward me the serial number as soon as you're able? Once I have that, I can begin the investigation on our end. Thanks.\n\n", name, partNum, desc);
    }
}
else if (strcmp(&ans2, "y")==0)
{
printf("Will Blank be sending the customer a replacement? Please enter y or n\n");
scanf("\n%c", &ansRep);

        if (!strcmp(&ansRep, "y")==0)
        {
            fprintf(fptr, "Blank can send you a replacement product as soon as is possible. In order to ensure that the replacements are shipped to the correct address, will you please confirm you shipping address via email? Thanks.\n\n");
            fprintf(fptr, "Thank you for your assistance in resolving this matter. Please let us know if you have any additional questions, comments, or concerns about this specific issue or any issues related to products distributed by Blank.\n\n");
fprintf(fptr, "Have a great day!");
        }
        else 
        {
            fprintf(fptr, "Thank you for your assistance in resolving this matter. Please let us know if you have any additional questions, comments, or concerns about this specific issue or any issues related to products distributed by Blank.\n\nHave a great day!");
        }
}
fclose (fptr);
return (0);
}

if (!strcmp(&ans1, "y")== 0) is wrong, which may be modified to if(ans1 != 'y') . You should do similar modifications to if (!strcmp(&ans2, "y")==0) , if (strcmp(&ans2, "y")==0) , if (!strcmp(&ansRep, "y")==0) in your code.

And for scanf("%c", &ans1); , you may rewrite it as follows:

scanf(" %c", &ans1);

First things first: ans1 and ans2 are chars; you are doing strcmp(&ans2, "y") - here, "y" is a string (NULL terminated array of characters) because it is in double quotes. Before anything else, you should replace all your comparisons of those variables with something like

if(ans1 == 'y')

Also, when you read a character you should add a space in front of the %c just in case there is some whitespace or a stray new line from previous input - scanf(" %c", &ans1);

除去\\nscanf("\\n%s" [...]和之前加入的空间%cscanf("%c"scanf("\\n%c"除去\\n )可以帮助。

you could create a simple function to catch strays from scanf

void clear_input_buffer(void)
{
    char buffer[100];
    fgets(buffer, 100, stdin);
}

then include it after scanf

scanf("%s", name);
clear_input_buffer();

Short answer: I think your strings contain garbage!

Strings in C must be terminated by a Null byte ('\\0'). When you create a char array on the stack (or heap) the contents of that array may be filled with whatever junk your memory happened to have at the time. Try running this small program to see what I mean. One might predict this program will print 3 blank lines, but it should instead print 3 lines of random garbage (every time you run this program the garbage should be different).

#include <stdio.h>

int main(){

char name[32];
char partNum[32];
char desc[250];

printf("%s\n", name);
printf("%s\n", partNum);
printf("%s\n", desc);

}

There are a few things you could improve in the program you've posted, but to specifically address your string containing garbage, here is a simple solution:

Replace lines like char name[32]; to char *name = calloc(32, sizeof char); and be sure to free these memory allocations at the end of your program like this free(name) .

calloc sets all the memory it allocates to NULL so your strings will no longer contain garbage.

If you are experiencing garbage in your output file, that should do the trick.

Also note

You are using fixed size char arrays. What happens if a user decides to type something in thats longer than you expected? The input will bleed into other parts of memory and can affect the values of other variables.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM