#include <stdio.h>
#include <string.h>
struct candidate
{
char candidateName[20];
int votes;
};
Initialize()
{
char firstname[10];
char lastname[10];
FILE* ifp;
int i;
struct candidate electionCandidates[7];
ifp = fopen("elections.txt", "r");
for (i = 0; i<7; i++)
{
strcpy(electionCandidates[i].candidateName, "aaaaa");
electionCandidates[i].votes = 0;
}
for (i=0; i<7; i++)
{
memset(&firstname[0], 0, sizeof(firstname));
memset(&lastname[0], 0, sizeof(firstname));
fscanf(ifp, "%s %s", &firstname, &lastname);
strcat (firstname, " ");
strcat (firstname, lastname);
strcpy (electionCandidates[i].candidateName, firstname);
printf("%s", electionCandidates[i].candidateName);
}
}
int main()
{
Initialize();
return(0);
}
The above code is supposed to read first and last names from a file, and add them to the candidateName portion of the struct. When I run this program, it assigns and prints the begginning first and last name, but then immediately crashes.
The file is in the format of
first last
first last
first last
etc
I feel like this may have something to do with it not going to read the next line, but I do not know how to do so. Any help would be greatly appreciated.
Problems I see:
Problem 1
The line:
fscanf(ifp, "%s %s", &firstname, &lastname);
is a problem if the first name and/or the last name in the input file is longer than 9 characters.
To take care of that problem, specify the maximum number of characters you want to read. Also, from a type point of view, use firstname instead of &firstname.
fscanf(ifp, "%9s %9s", firstname, lastname);
Problem 2
The lines
strcat (firstname, " ");
strcat (firstname, lastname);
is a problem if length of firstname + length of lastname is greater than 8.
You can use:
strcpy (electionCandidates[i].candidateName, firstname);
strcat (electionCandidates[i].candidateName, " ");
strcat (electionCandidates[i].candidateName, lastname);
to solve that problem.
Related
In this code, I am facing a problem that is whenever I try to enter the first and last name, it only prints the first name in the file. But I want to print the last name also. The space between the two words should not be removed. Instead first and last should be considered as one.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp = fopen("new.csv", "w");
char name[50];
printf("Enter your name: ");
scanf("%s", name);
fprintf(fp, "%s", name);
fclose(fp);
return 0;
}
If you use %s, fscanf read until a whitespace character appear, stopping after the first name.
If there's nothing else at the line e.g. before the user presses Enter, you could use fgets to read in the whole line. The parameters there are the file stream, a pointer to the character array and it's size:
char name[50];
fgets(stdin, name, sizeof(name));
If you still want to use scanf, you could also use %[^\n] instead of %s as mentioned here:
char name[50];
scanf("%49[^\n]", name);
To prevent buffer overflow, you should use scanf only with the buffers size minus one written directly after % (defining maximum field width).
If there's other data in the line after first and last name, you could read them in separately and put them together afterwards:
#include <stdio.h>
int main() {
char firstName[50];
char lastName[50];
scanf("%49s %49s", firstName, lastName);
char name[50];
snprintf(name, sizeof(name), "%s %s", firstName, lastName);
printf("%s\n", name);
}
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void get_name();
void display_name(char *fullname);
int main(void)
{
char first[80];
char second[80];
char *fullname[80];
get_name();
display_name(*fullname);
system("pause");
return 0;
}
void get_name()
{
char first[80];
char second[80];
char *fullname[80];
printf("Please enter first name: ");
scanf("%s", &first);
printf("\nPlease enter last name: ");
scanf("%s", &second);
strcpy(*fullname, first);
strcat(*fullname, " ");
strcat(*fullname, second);
printf("\n\nFull name is : %s ", *fullname);
}
void display_name(char *fullname)
{
int index;
char check;
int count=0;
printf("\n\nFull name is : %s ", fullname); //check to see if string is passes correctly
for(index=0; fullname[index] != '\0'; index++)
{
check=fullname[index];
if(check != ' ')
{
count++;
}
}
printf("\n\nNumber of characters in string is: %i\n", count);
}
im trying to send the string from get_name() to display name to count the number of characters. Everytime i pass the string, its comes out as gibberish. Am i passing wrong? I need to use one function to get the first and last name and concatenate the full name, then use another function to count the number of characters.
You're using pointers and scanf quite wrongly.
First of all scanf argument to for %s is supposed to be an array of characters. Remember that the array is in fact the pointer to the array.
Second you declare fullname to be an array of 80 pointers which is probably not what you want to do. Especially when you don't allocate the space for the string.
Instead it should be something like:
void get_name()
{
char first[80];
char second[80];
char fullname[80]; // an array of chars instead of pointers
printf("Please enter first name: ");
scanf("%s", first); // not taking the address of first - is already an address
printf("\nPlease enter last name: ");
scanf("%s", second); // not taking the address of second - is already an address
strcpy(fullname, first); // don't dereference fullname
strcat(fullname, " "); // don't dereference fullname
strcat(fullname, second); // don't dereference fullname
printf("\n\nFull name is : %s ", fullname); // don't dereference fullname
}
The declarations of variables are local to the scope where they are declared.
IOW when you declare first, second and fullname in your function get_name, they are local to that function. In order to pass the value outside of the function you have two, no three ways to do this starting with the worst way:
(1) declare the variable global, i.e. outside of main then share that variable in your function(s).
(2) declare the variable in main but pass it to the function who then fills in the string
int main()
{
char fullname[80];
get_name(fullname,sizeof(fullname)); // good to tell function avail size
...
void get_name(char* fullname, size_t length)
{
...
(3) Allocate memory on the heap, heap memory can be passed around between functions via a pointer
int main()
{
char* fullname = NULL;
get_name(&fullname);
...
void get_name(char** fullname)
{
*fullname = malloc(80);
...
EDIT
In order to read strings from the keyboard it is better to use fgets()
char buffer[128];
if (fgets(buffer,sizeof(buffer),stdin) != NULL) {
// remove the \n
char* p = strchr(buffer,'\n');
if ( p != NULL ) {
*p = '\0';
}
}
Using scanf reading from the keyboard is to be avoided, if you need to extract information use instead sscanf on the string read with fgets
When I give the input then only first alphabet is showing.
I want to print the complete name which is I just entered.
#include <stdio.h>
int main()
{
char name;
char grades;
int i;
printf("Name of the Student:");
scanf("%c",&name);
printf("Name your Just entered is : %c",name);
return 0;
}
I agree with the others - but add some error checking and ensure no buffer overruns i.e
#include <stdio.h>
int main() {
char name[101];
printf("Name of the student:");
if (scanf("%100s", &name) == 1) {
printf("Name you just entered: %s\n", name);
return 0;
} else {
printf("Unable to read name of student\n";
return -1;
}
}
EDIT
As you have edited the question so that it does not have the same meaning as before I will leave my previous solution here.
But what you want is to use fgets - this allows for white space in the name
ie.
#include <stdio.h>
int main()
{
char name[100];
printf("Name of student:");
fflush(stdout);
fgets(name, 100, stdin);
printf("Students name is %s\n", name);
return 0;
}
Replace char name; with char name[100];. This will define name as array of chars, because you handled with it as single character.
For scanf replace it with scanf("%s",&name[0]);, and printf with printf("Name your Just entered is : %s",name);. %s means string, so it will scan whole string, not just single character. In scanf &name[0] points to beginning of array.
You need to scanf into an array, rather than into a single character:
#include <stdio.h>
int main() {
char name[100];
printf("Name of the student:");
scanf("%s", &name);
printf("Name you just entered: %s\n", name);
}
You are trying to store a array of characters(string) in a character. So only the first character is taken.To rectify this initialize the name as:
char name[40];
take input as :
scanf("%s",name);
and print as:
printf("name is %s",name);
name is a char and scanf will only catch one character when you use %c. You can use a char array to store the name instead :
char name[40];
/* edit the size for your need */
Also edit your scanf and printf to use a %s
You are reading (and printing) a single char using %c. If you want to handle stirngs, you should use a char[] and handle it with %s:
#include <stdio.h>
int main()
{
char name[100]; /* Assume a name is no longer than 100 chars */
char grades;
int i;
printf("Name of the Student: ");
scanf("%s",&name);
printf("Name your Just entered is : %s",name);
return 0;
}
I want to take the first letter from my firstname string variable and add it to the second letter of the lastname variable.
My program so far is:
#include <stdio.h>
main() {
char firstname [256];
char lastname [256];
printf("What's your first name?: ");
scanf("%c",&firstname);
printf("What is your last name? ");
scanf("%s",&lastname);
printf("\nYour school.edu e-mail address is: %c%s2#school.edu",firstname,lastname);
return 0;
}
However, I would like for my code to take the first initial (the first letter of the first name) and store it into the firstname variable.
As strings are array of characters, you need to take the first element from the array:
char firstname_initial;
firstname_initial = firstname[0]
Also note that since lastname and firstname are buffers, you don't need to pass a pointer to them in scanf:
scanf( "%s", firstname );
scanf( "%s", lastname );
And one last thing - scanf is a dangerous function and you should not use it.
Suppose the user types:
Michael
in response to the first prompt. The %c format reads the M; the %s format reads ichael without bothering to get any new data.
Also, you should not be passing &firstname or &lastname; you should be passing just firstname and lastname to scanf(). The difference is in the type; with the ampersand, you're passing a char (*)[256] which is not the same as the char * that scanf() expects. You get away with it, but 'get away with it' is the operative term.
Use a %s format (or, better, %255s format) for the two scanf() calls. Then pass firstname[0] and lastname to printf(). You might want to think about using tolower() from <ctype.h> on the first letter, and maybe on the last name too.
This is a reasonable approximation to a good program:
#include <stdio.h>
int main(void)
{
char firstname[256];
char lastname[256];
printf("What's your first name? ");
if (scanf("%255s", firstname) != 1)
return 1;
printf("What's your last name? ");
if (scanf("%255s", lastname) != 1)
return 1;
printf("Your school.edu e-mail address is: %c%s2#school.edu\n",
firstname[0], lastname);
return 0;
}
It avoids quite a lot of problems, one way or another. It is not completely foolproof, but most people won't run into problems with it.
I think you want the variable firstname to store only the initial.
So that firstname act like string.
firstname[1] = '\0'; //mark the end of string on second character
printf("\nYour school.edu e-mail address is: %s%s2#school.edu",firstname,lastname);
#include <stdio.h>
#include<string.h>
main() {
char firstname [256];
char lastname [256];
char str [50];
printf("What's your first name?: ");
scanf("%s",firstname);
printf("What is your last name? ");
scanf("%s",lastname);
str = strcpy(str, firstname[0]);
str = strcpy(str,lastname[1]);
printf("\nYour school.edu e-mail address is: %s2#school.edu",str);
return 0;
}
Copy first char from c string
char extractedchar = '0';
extractedchar=myoldstring[0];
Note : the char '0' is there just to test later in the application
Assuming expected input:
fname = Batman
lname = Joker
Expected Output:
Your school.edu e-mail address is: BJBker2#school.edu
Try this:
void main( void )
{
char fname = 0;
char lname[256] = {0};
printf("Enter firstname\n");
scanf("%c", &fname);
printf("Enter lastname\n");
scanf("%s", lname);
lname[1] = fname;
printf("Your school.edu e-mail address is: %c%s2#school.edu\n", fname, lname);
return;
}
So I want to make the hello.c program write both the first name and the last name on one line so in this form but when I run my program in this current form it gives me the error "expected â)â before string constant" I think I have the rest of the code down because I have removed that line and ran it and it works. So I just want to ask how to get 2 strings that I have already pointed to to go on the same line.
This is my code
#include <stdio.h>
int main()
{
char firstname[20];
char lastname[20];
printf("What is your firstname?");
scanf("%s", firstname);
printf("What is your lastname?");
scanf("%s", lastname);
printf("Hello %s\n", firstname "%s", lastname);
printf("Welcome to CMPUT 201!");
}
You want
printf("Hello %s %s\n", firstname, lastname);
instead of
printf("Hello %s\n", firstname "%s", lastname);
#include<stdio.h>
#include<string.h>
int main()
{
char first_name[20] = " ", last_name[20] = " ", full_name[40] = " ";
printf("What is your firstname?\n");
scanf("%s", first_name);
printf("What is your lastname?\n");
scanf("%s", last_name);
sprintf(full_name,"%s %s",first_name, last_name);
printf("name is %s\n",full_name);
return 0;
}
I have shown the same using sprintf.
1) also in your program you are not returning anything, if dont want to return anything make it as void function. When you write int function, always make it an habbit to return the integer.
2) Also when you write the printf function always make it habit to add \n(new line) so the output looks good
happy coding.