Printing out exact character value when using array in C programming - arrays

I enter two names in this case 'Jack' and 'Sara' and when i want to printout
'Jack' and 'Sara', This only prints out the last name which is sara im just wonderig how can i solve this problem even i wanna use more names here is the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[20];
int i;
printf("\n\n");
for(i = 1; i <= 2; i++)
{
printf("Person.%d FristName: ", i);
scanf(" %s", name);
}
printf("\n\nHi %s \n", name);
printf("Hi %s \n", name);
return 0;
}
And here is the Output:
Hi Sara
Hi Sara

Related

Array of strings concatenating positions

I am programming a registration system using array strings for postal code and home address. I use a constant to determine the postal code limit of just 8 characters.
When the program start the register function, it makes the address and postal code inputs correct, but when I list it, the address appears normal and the postal code of position 1 together with the others below. Why is this happening? I put 8 character positions for the postal code and it increases by placing the second one as well.
My program:
#include <stdio.h>
#define LIMIT_POSTAL 8
#define LIMIT_REGISTER 5
#define LIMIT_ADDRESS 20
char postal_c[LIMIT_REGISTER][LIMIT_POSTAL], address[LIMIT_REGISTER][LIMIT_ADDRESS];
int line;
void reg()
{
int op;
do
{
printf("Address: ");
scanf("%s", &address[line]);
printf("Postal code: ");
scanf("%s", &postal_c[line]);
op = -1;
printf("1 - Continue\nAny number - Exit\n");
scanf("%d", &op);
line++;
} while(op == 1);
}
int main()
{
int i;
reg();
for(i = 0; i < line; i++)
{
printf("Address: %s\n", address[i]);
printf("Postal: %s\n", postal_c[i]);
}
return 0;
}
Output:
Address: foo
Postal code: 11111111
1 - Continue
Any number - Exit
1
Address: foo2
Postal code: 22222222
1 - Continue
Any number - Exit
0
Address: foo
Postal: 1111111122222222
Address: foo2
Postal: 22222222
In your code probably:
#include <stdio.h>
#define LIMIT_POSTAL 8
#define LIMIT_REGISTER 5
#define LIMIT_ADDRESS 20
char postal_c[LIMIT_REGISTER][LIMIT_POSTAL], address[LIMIT_REGISTER][LIMIT_ADDRESS];
int line;
void reg()
{
int op;
do
{
printf("Address: ");
scanf("%s", &address[line]);
printf("Postal code: ");
scanf("%s", &postal_c[line]);
op = -1;
printf("1 - Continue\nAny number - Exit\n");
scanf("%d", &op);
line++;
} while(op == 1);
}
int main()
{
int i;
reg();
for(i = 0; i < line; i++)
{
printf("Address: %s\n", address[i]);
printf("Postal: %s\n", postal_c[i]);
}
return 0;
}
I can't see you had initialized line variable in you program and you are using it directly to pointing the index, hence you didn't assigned any value so probably it contains garbage value and pointing invalid memory address in your program.
I am assuming your rest code is correct.
try doing...
int line =0;

Unwanted output on second pass using strcpy

I'm reading a book called "C programming Absolute Beginners Guide."
The following program uses some if loops and strcpy to store some character arrays provided by the user. The first pass of strcpy works fine. The second produces garbage. I understand the array needs a \0 to end. According to the book, strcpy does this automatically. What am I missing?
#include <stdio.h>
#include <string.h>
main()
{
int ctr, numMovies, rating, favRating, leastRating;
char movieName[40], favorite[40], least[40];
favRating = 0;
leastRating = 0;
do {
printf("How many movies have you seen this year? ");
scanf(" %d", &numMovies);
if (numMovies < 1)
{
printf("No movies! How can you rank them?\nTry again\n\n");
}
} while (numMovies < 1 );
for (ctr = 1; ctr <= numMovies; ctr++)
{
printf("\nWhat's the name of the movie? ");
printf("(1-word titles only!) ");
scanf(" %s", movieName);
printf("On a scale of 1 to 10, what would ");
printf("you rate it? ");
scanf(" %d", &rating);
if (rating > favRating)
{
strcpy(favorite, movieName);
favRating = rating;
}
printf("%s", movieName);
if (rating < leastRating)
{
strcpy(least, movieName);
leastRating = rating;
}
}
printf("\nYour Favorite Movie was %s.\n", favorite);
printf("\nYour Least-favorite movie was %s.\n", least);
return 0;
}
Because you initialize leastRating to zero you won't have a least favorite unless the rating is negative. Not sure that's what you want.
The best suggestion is from #xing, add a include
#include <limits.h>
and initialize you best and worst like this;
favRating = INT_MIN;
leastRating = INT_MAX;

Lower to Upper Case Conversion with C

Problem Statement
I'm facing difficulty in solving a programming contest problem, which reads as follows:
You are given T name(s) in english letters. Each name will include some
of the uppercase letters from A to Z, some of the lowercase letters
from a to z and some spaces. You have to transform the name(s) from
lowercase to uppercase. Letters that are originally uppercase
will remain the same and the spaces will also remain in their
places.
Sample Input-Output
If I type this in...
5
Hasnain Heickal Jami
Mir Wasi Ahmed
Tarif Ezaz
Mahmud Ridwan
Md Mahbubul Hasan
the computer should output this...
Case 1: HASNAIN HEICKAL JAMI
Case 2: MIR WASI AHMED
Case 3: TARIF EZAZ
Case 4: MAHMUD RIDWAN
Case 5: MD MAHBUBUL HASAN
Note that exactly one space is required between the semi-colon and the initial letter of the name.
My Coding
This is what I've coded in C:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
int main(void)
{
int T, i;
char string [100];
scanf("%d", &T);
for (i=0; i<T; i++)
{
gets(string);
printf("Case %d: ", i);
while (string[i])
{
putchar (toupper(string[i]));
i++;
}
printf("\n");
}
getch();
return 0;
}
Now, this code fails to produce the desired output. Where am I doing it wrong? Is there any matter with my syntax? Can somebody guide me? Please bear in mind that I'm a middle-schooler and just a beginner in C.
You need to cycle over each letter of the string one-by-one.
In this code below, I have done that with variable K, which goes from 0 to the length of the string.
Variable I keeps track of the number of strings.
int main(void)
{
int T, i, k;
char string [100];
scanf("%d", &T);
for ( i = 0; i < T; ++i)
{
gets (string);
for(k=0; k<strlen(string); ++k)
{
putchar (toupper(string[k]));
}
}
getch();
return 0;
}
In response your question: IDEOne Link
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
int T, i,k;
char string [100];
scanf("%d ", &T);
for ( i = 0; i < T; ++i)
{
gets (string);
printf("[%d] : %s\n", i, string);
for(k=0; k<strlen(string); ++k)
{
putchar (toupper(string[k]));
}
putchar('\n');
}
return 0;
}
Please go through the code and implement the test cases scenarios as per your requirement.
#include <stdio.h>
#include<string.h>
int main(){
char string[100];
int i;
scanf("%s",string);
for(i=0;i<strlen(string);i++){
string[i]=string[i]-32;
}
printf("%s",string);
return 0;
}

Storing Data Char Array C

[I write the program in C language]
I would like to read a txt file containing StudentName, Score, and Remarks
The pattern of the txt file looks like this:
1,Adam Lambert,60,C
2,Josh Roberts,100,A
3,Catherine Zetta,80,B
I would like to store each data, respectively into an array
So I would have 3 arrays (to store StudentName, Scores, and Grades)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <math.h>
char* studName[99];
char* grade[99];
char* grades[100][10];
char buff[1024];
int scores[100];
int score;
int index;
int size;
int index = 0;
int sum = 0;
double average = 0;
int main()
{
FILE *file;
file = fopen("notepad.txt", "r");
if(file == NULL){
printf("Data does not Exist");
}
else {
while(((fgets(buff,1024,file))!=NULL))
{
size = strlen(buff);
buff[size] = 0;
sscanf(buff, "%d, %[^,],%d, %[^,]", &index, studName,&score, grade);
printf("Student Name: %s\n", studName);
printf("Score: %d\n", score);
printf("Remark: %s\n", grade);
scores[index-1] = score;
grades[index-1][10] = grade;
sum+=score;
index++;
}
}
fclose(file);
average = sum/index;
printf("\nThe total score of student is: %d\n", sum);
printf("\nThe sum of student is: %d\n", index);
printf("\nThe average of students' score is: %2f\n", average);
for(int i = 0; i<3; i++){
printf("Score: %d\n", scores[i]);
printf("\nThe Remark is: %s\n", grades[i][10]);
}
getch();
return 0;
}
The code above had successfully stored the scores in int array. I had not really good in C, so I do not know how to store the char array for StudentName and Grades.
The abovde code gives the result of Grades stored is only the last grade on the txt file (in this case is 'B').
Would you please tell me what do I have to fix in order to achieve my goal?
My goal basically will be pretty much like this:
StudentName array contains {"Adam Lambert", "Josh Roberts", "Catherine Zetta"}
Scores array contains {60,100,80}
Grades array contains {"C", "A", "B"}
Thank you very much.
Change studName and grade from "char *" to "char". You want a buffer, not an array of pointers.
At the top add:
char * StudentName[100];
When setting "scores" and "grades" add:
StudentName[index-1] = strdup(studName);
Also change the "10" in the following line, the array only dimensions 0-9.
grades[index-1][10] = grade;
Try this:
float len=sizeof(string);
Just gives you the static size of the array string which is an array of 20 pointers and each pointer is 4 bytes, 20 * 4 bytes = 80 that's why it's always 80.
while (fgets(string[i], BUFSIZE, fp)) {
i++;
len+=strlen(string[i]);
string[i] = (char *)malloc(BUFSIZE);
}
If your recore size is fixed then u can use this:
Where fr is a file pointer
fscanf(fr, "Index: %d StuName: %s Score: %d Grade: %s ", &index, sname, &score, grade);

C Language - Printing array into text file

I am trying to make a program in the C language that can take in employee information in array struct (not parallel) form and output it into a text file.
The program will compare the job code and calculate the commission rate of the employee.
I have 2 questions:
1 - the commission of the salesPerson is always 0 even when I enter one of TEL, SAL, SSR. Is it a problem with my string comparison?
2 - how do I output my results into a text file (inside the project folder)?
Edit - I have figured out how to print my file into a txt. Thank you all for your help!
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
//job codes
char TEL[4] = "TEL";
char SAL[4] = "SAL";
char SSR[4] = "SSR";
//create a sales person structure
struct salesPerson
{
char name[31];
int salesID;
char jobCode[4];
double totalSales;
double commission;
}e[10]; //make an array of 10 employees
int _tmain(int argc, _TCHAR* argv[])
{
//get employee info
for(int i=0; i<3; i++)
{
printf("\nEnter the sales person's name: ");
scanf(" %s", &e[i].name);
printf("\nEnter the sales person's ID: \n");
scanf(" %d%*c", &e[i].salesID);
printf("\nEnter the sales person's job code: \n");
scanf(" %s", &e[i].jobCode);
printf("\nEnter the total sales of the sales person: ");
scanf(" %lf", &e[i].totalSales);
//determine commission based on jobCode
if(strcmp(e[i].jobCode, TEL) == 0)
{
e[i].commission = e[i].totalSales*0.02;
}
if(strcmp(e[i].jobCode, SAL) == 0)
{
e[i].commission = e[i].totalSales*0.05;
}
if(strcmp(e[i].jobCode, SSR) == 0)
{
e[i].commission = e[i].totalSales*0.07;
}
else
{
printf("\n----------");
}
}
printf("\n%d\n", e[0].commission);
printf("\n%d\n", e[1].commission);
printf("\n%d\n", e[2].commission);
//print stuff to txt file
FILE *fpOut, *fpIn;
/*
if ((fpIn = fopen("c:\\temp\\salesEmployees.txt", "w")) == NULL)
{
printf("Error opening the file for processing\n\n");
}
else
{
fpOut = fopen("c:\\temp\\salesEmployees.txt", "w");
for(int i=0; i<3; i++)
{
//fscanf(fpIn,"%[^\n]", &e[i].name);
//fscanf(fpIn,"%f%*c", &e[i].salesID);
fprintf(fpOut, "\nName: %s", e[i].name);
fprintf(fpOut, "\nSalesID: %d*c ", e[i].salesID);
fprintf(fpOut, "\nJob code: %s ", e[i].jobCode);
fprintf(fpOut, "\nTotal sales: %.2lf", e[i].totalSales);
fprintf(fpOut, "\nCommission earned: %.2lf", e[i].commission);
fprintf(fpOut, "\n\n");
}
//fclose(fpOut);
}*/
}
To answer the second part of your question (about program crashing, and keeping file in same directory): you open the same file for input and output without closing in between; not sure why the input is even there. Assuming (for simplicity) that you only want to save to file what was entered from the keyboard, you can just remove all reference to the fpIn. As for the "keep file in same folder" - just use a relative path. When you run from c:\my\dir, then opening a file salesOutput.txt will cause it to be written to c:\my\dir\salesOutput.txt.
Complete and working code (some changes to accommodate my compiler settings...):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//job codes
char TEL[4] = "TEL";
char SAL[4] = "SAL";
char SSR[4] = "SSR";
//create a sales person structure
struct salesPerson
{
char name[31];
int salesID;
char jobCode[4];
double totalSales;
double commission;
}e[10]; //make an array of 10 employees
int main(int argc, char* argv[])
{
//get employee info
int i;
for(i=0; i<3; i++)
{
printf("\nEnter the sales person's name: ");
scanf(" %s", &e[i].name);
printf("\nEnter the sales person's ID: \n");
scanf(" %d%*c", &e[i].salesID);
printf("\nEnter the sales person's job code: \n");
scanf(" %s", &e[i].jobCode);
printf("\nEnter the total sales of the sales person: ");
scanf(" %lf", &e[i].totalSales);
//determine commission based on jobCode
if(strcmp(e[i].jobCode, TEL) == 0)
{
e[i].commission = e[i].totalSales*0.02;
}
if(strcmp(e[i].jobCode, SAL) == 0)
{
e[i].commission = e[i].totalSales*0.05;
}
if(strcmp(e[i].jobCode, SSR) == 0)
{
e[i].commission = e[i].totalSales*0.07;
}
else
{
printf("\n----------");
}
}
printf("\n%lf\n", e[0].commission);
printf("\n%lf\n", e[1].commission);
printf("\n%lf\n", e[2].commission);
//print stuff to txt file
FILE *fpOut;
{
if((fpOut = fopen("salesEmployees.txt", "w")) == NULL)
{
printf("Unable to open file - quitting\n");
return -1;
};
int i;
for(i=0; i<3; i++)
{
fprintf(fpOut, "\nName: %s", e[i].name);
fprintf(fpOut, "\nSalesID: %d*c ", e[i].salesID);
fprintf(fpOut, "\nJob code: %s ", e[i].jobCode);
fprintf(fpOut, "\nTotal sales: %.2lf", e[i].totalSales);
fprintf(fpOut, "\nCommission earned: %.2lf", e[i].commission);
fprintf(fpOut, "\n\n");
}
fclose(fpOut);
}
}
Obviously it is desirable (and necessary) to add addition I/O, error checking on inputs, etc - but this should get you past the point of "it's not working and I don't know why". I did wonder why you have the *c in the printout of the sales ID - it just gets added to the output - but I decided not to remove it.
Good luck with the coding!
Always look at the warnings from your compiler. You have
printf("\n%d\n", e[0].commission);
Where you give an integer format specifier, but the argument is double. The first few bytes of that may well be zero - which is why the result prints as zero. Try changing it to:
printf("\n%.2lf\n", e[0].commission);
And you will get the commission in dollars and cents. Same for the other lines.

Resources