Why does code yields no results on this char comparison? - c

Evening, sorry for beginner question but I have to do a code that receives 7 salutations in different languages, compare to a database, and, if they match, tell which language the salutation was on, if they don't, tell the user the language is unknown.
I think i understood the problem, but my code below doesn't show any results and just closes, can someone tell me why? I know it is very sketchy coding but cant find exactly the mistake. (Telling me a substitute for the multiple variables inside scanf would be much appreciated too).
#include<stdio.h>
#include<string.h>
int main(){
char en[7][15];
char id[7][15] = {"HELLO","HOLA","CIAO","HALLO","BOUNJOUR","ZDRAVSTVUJTE","."};
char re[7][15] = {"INGLES","ESPANOL","ITALIANO","ALEMAN","FRANCES","RUSO","NLS"};
scanf("%s %s %s %s %s %s %s",en[0],en[1],en[2],en[3],en[4],en[5],en[6]);
int i = 0,j=0,m=1,k=0;
while(i<8){
for(j=0;j<7;j++){
m=strcmp(en[i],id[j]);
if(m==0 || j==6){
strcpy(en[i],re[j]);
k=i+1;
printf("Caso %s: %s /n",k,en[i]);
break;
}
}
i++;
}
}
Thank you

The problem is your printf function. You are using %s format specifier for k instead of %d. Just change that line to this:
printf("Caso %d: %s \n",k,en[i]);
Also, the while condition i<8 should be changed to i<7 since there are 7 cases and not 8.
As for the scanf, don't think it's much of an improvement but you can use a for loop as well.

Related

printf Function not giving output in C

I am an absolute newbie, and I am learning to code.
#include <stdio.h>
#include <stdlib.h>
int main(){
char characterName[] = "Khan";
int characterYear = 2022;
float characterScore = 8.8;
char characterGrade = 'A';
printf("%s passed out of college in %d and had a grade of %s i.e. a score of %f\n",characterName,characterYear,characterGrade,characterScore);
return 0;
}
Can someone help me with this — I was just trying to incorporate all simple data types in one line (for reference) and after I run the program there is no output whatsoever, it just exits! It didn't happen when I had fewer data types in the line.
P.S. This might be the dumbest ever question ever asked on Stack Overflow, but please forgive if I am dumb/silly :)
Your format is wrong:
characterGrade has type char and you want to print it using %s format which requires char * parameter. It has to be %c instead:
"%s passed out of college in %d and had a grade of %c i.e. a score of %f\n"

reading string with spaces and then integers from same line in file

so the title says everything and i created a VERY simple code just to test this, and i cant get it to work.
The file has one line and it is "asd dsa:1 2 3"
i want to store "asd dsa" in a string variable, and each number in a different int variable.
this is the code:
#include<stdio.h>
int main(){
FILE *fp;
fp=fopen("file.dat","r");
char aa[20];
int a, b, c;
fscanf(fp, "%[^:]%d %d %d", aa, &a, &b, &c);
printf("%s %d %d %d\n", aa, a, b, c);
return 0;
}
and the output is
asd dsa 21911 1313271752 32720
so it is reading only the string.
I highly suggest in the future to learn how to debug your code. To be honest, I did not found the solution right at the top so I copied the code, and ran in on my machine and I got the wrong output, like you. Then, I debugged my code and I noticed the string is read correctly, and the numbers remain untouched. To make sure, I created a variable to hold the return value from scanf, and indeed it was 1 since only the string was getting the input.
I then first tied to add a space between %[^:] and %d, but to no avail. Then I looked at the file again, and the string I got on aa variable and noticed the : was in the file, but not in aa. Where did it go? nowhere, it was still in the buffer waiting to be read. In order to "skip" it, you could just add : sign after %[^:], so the command would "eat it", and after doing it on my machine it worked.
The short answer, is to change the scanf line to:
fscanf(fp, "%[^:]:%d %d %d", aa, &a, &b, &c);
The long answer, is to learn how to debug you code correctly, It took my less than 2 minutes to figure it out and I'm sure that if you tried yourself, you could find the solution too.
Of course if you try debugging yourself with no avail, you are always welcome to open a topic!

Whats wrong with my user input in C

I know python decently well, I've been trying to learn C for the past ~4 days. I found this code online edited it a tad bit and now it won't run.
#include <stdio.h>
#define MAX_LEN 80
int main (int argc, char *argv[]){
char a_word[MAX_LEN];
printf ("Enter some words:");
scanf ("%s", a_word);
printf ("The result is:" + a_word);
return 0;
}
There is nothing wrong with scanf(), the issue here is with printf() statement. In C, you need to have a format specifier to print the supplied arguments. Read the man page of printf() for further information.
In your code,
printf ("The result is:" + a_word);
should be
printf ("The result is: %s \n" , a_word);
In C, you cannot append strings with +. To append strings, use strcat() or one of the other functions for this purpose. In your concrete example however, you can just do, as Sourav Ghosh already wrote do:
printf("The result is: %s \n" , a_word);

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);
Removing \n in scanf("\n%s" [...] and adding a space before %c in scanf("%c" and scanf("\n%c" (removing \n) may help.
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();
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);
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.

scanf and printf format modifiers

I need help on this exercise from C Primer Plus.
Write a program that requests your first name and does the following with it:
Prints it in a field three characters wider than the name
#include<stdio.h>
#include<string.h>
int main()
{
char a[40];
int p,v=0;
printf("Enter your first name: \n");
scanf("%s",a);
p= strlen(a);
v==p+3;
printf("%s",a);
}
I cant figure out how what to use as a modifier for the width
what should I add in between % and s?
the goal of this excercise is to read and grok the manual page for printf(). The reading part could only be done by you and there is no shortcut. The format specifier is the most complex chapter in C-Programing (other would say 'pointer'), and it is very wise to know where look things up (man-page) in need of remembering.
When you are done reading, you should have a little (or big) understanding of the format-specifier %s with all its possibilities.
EDITH: when you are done reading, and there is still a question whether to use "%*.*s" or "%s" or "%-.*s" etc., please come back with an updated question.
Here is one way to do it:
#include<stdio.h>
#include<string.h>
int main()
{
char a[40];
printf("Enter your first name: \n");
scanf("%s",a);
printf("[%-*s]", (int)(3 + strlen(a)), a);
return(0);
}
The printf() function can do it all.
From the question code, it is clear that "%s" as a format string is understood.
A format string of "%*s" allows the caller to place the (space-padded) width to be specified. For example:
printf("%*s", 10, "Hello");
The above will print "Hello" (as expected), in a 10-character frame. Hence, the command above actually prints: " Hello".
To put the spaces on the other side, tell printf() to left-justify the string using:
printf("%-*s", 10, "Hello");
This results in printing: "Hello "

Resources