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;
}
Related
int main()
{
int Age;
char Name;
//Age
printf("Type your age: ");
scanf_s("%d", &Age);
printf("Your age is %d\n", Age);
//Name
printf("Type your Name: ");
scanf_s("%s", &Name);
printf("Your name is %s", Name);
return 0; }
It's the 'Name' section which is throwing out an error. I can't figure out why.
UPDATE: I'm coding in Visual Studio. Therefore, "scanf_s" is essentially required.
The error is "Exception thrown at 0x5B49D4EC (ucrtbased.dll) in Project1.exe: 0xC0000005: Access violation writing location 0x001A0000. occurred"
Your problem is that char Name; can only store a single character. Your code is allowing the user to type in multiple characters which are being stored into Name causing a memory error.
Change char Name; to something like char Name[50] so that you can store up-to 49 characters plus the null byte.
Also you should use scanf_s() properly to avoid the error if the buffer (char array) ends up being too small.
Note, you should always check the return from scanf_s() so you know if the user entered valid data or not.
This code works correctly in Visual Studio:
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
int main()
{
int Age;
char Name[50];
printf("Type your age: ");
if(scanf_s("%d", &Age))
{
printf("Your age is %d\n", Age);
printf("Type your Name: ");
if (scanf_s("%s", Name, (unsigned)_countof(Name)))
{
printf("Your name is %s\n", Name);
}
else
{
printf("Name:: Invalid Input\n");
}
}
else
{
printf("Age:: Invalid Input\n");
}
return 0;
}
The problem is that you defined Name as a char - a single character - but you are trying to use it as a string (multiple characters).
To fix this you must either (a) define Name as an array of characters (which would be a string) - such as char Name[100]; or (b) as a pointer (such as char *Name;) - which would require you to malloc() the string before use and free() it after use.
Strings can be tricky, as they are basically just arrays of chars, but that requires you to either know, or find a way to know, how many characters will be in the string. You can read more about how to do that here, in the documentation for scanf_s, which gives this example:
char c[4];
scanf_s("%4c", &c, (unsigned)_countof(c)); // not null terminated
First off I would just use scanf(), not scanf_s().
Furthermore you need to cast your Name variable as a string, which is an array of characters as I have defined it below. Using just char Name, means you have created a variable with room for just one character.
Hope this helps :)
int main()
{
int Age;
char Name[10];
printf("Type your age: ");
scanf("%d", &Age);
printf("Your age is %d\n", Age);
//Name
printf("Type your Name: ");
scanf("%s", &Name);
printf("Your name is %s", Name);
return 0;
}
Fixed the problem by going to...
Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically.
Thanks for everyone's help :)
#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
I am trying to learn to program in C but am having trouble with manipulating strings as C treats strings as arrays.
My aim was to make a program that stores the users first name and surname.
Here is my progress:
#include <stdio.h>
int main(int argc, const char * argv[]) {
//defining the variables
char first_name[100];
char surname[100];
char ch[2];
// Asking for the first name and storing it
printf("What's your first name?\n");
scanf("%s", first_name);
// Prints the first name
printf("Hey %s!\n",first_name);
//Asks the user if they want to store their surname
printf("Would you like to tell me your second name? This is optional so type 'Y' for yes and 'N' for no.\n");
scanf("%s", ch);
//validate if they want to store it or not
if (ch == "Y"){
printf("What is your surname?\n");
scanf("%s", surname);
printf("Your whole name is %s %s", first_name, surname);
}
return (0);
}
However, with this code, I get an error because my IDE(xCode) tells me to use the strcmp function. I then edited the code to become this:
if (strcmp(ch, "Y")){
printf("What is your surname?\n");
scanf("%s", surname);
printf("Your whole name is %s %s", first_name, surname);
}
However variable ch is not a literal and so is not comparable.
Sidenote
I did try to compare two literals too, just to see how it works:
char *hello = "Hello";
char *Bye = "Bye";
if (strcmp(hello, Bye)){
printf("What is your surname?\n");
scanf("%s", surname);
printf("Your whole name is %s %s", first_name, surname);
}
But even this gave an error:
Implicitly declaring library function 'strcmp' with type 'int (const *char, const *char)'
I believe I am not able to do this due to my lack of experience so it would be much appreciated if you could help me understand what I'm doing wrong and how I can fix the problem.
You need to include the appropriate header:
#include <string.h>
Also note that your desired logic probably calls for:
if (!strcmp(hello, Bye))
Instead of:
if (strcmp(hello, Bye))
Since strcmp returns 0 in case of equality.
There are several issues you should correct concerning how you handle input with scanf. First always, always validate the number of successful conversions you expect by checking the return for scanf. Next, as mentioned in the comment, there is NO need to include <string.h> in your code to make a one-letter comparison. Use a character comparison instead of a string comparison. Lastly, always limit your input to the number of characters available (plus the nul-terminating character.
Putting the bits together, you could do something like the following:
#include <stdio.h>
#define MAXN 100
int main (void) {
char first_name[MAXN] = "", surname[MAXN] = "";
int ch;
printf ("What's your first name?: ");
if (scanf ("%99[^\n]%*c", first_name) != 1) {
fprintf (stderr, "error: invalid input - first name.\n");
return 1;
}
printf ("Hey %s!\n", first_name);
printf("Enter surname name? optional (Y/N) ");
if (scanf("%c%*c", (char *)&ch) != 1) {
fprintf (stderr, "error: invalid input - Y/N\n");
return 1;
}
if (ch != 'y' && ch != 'Y') /* handle upper/lower case response */
return 1;
printf ("Enter your surname?: ");
if (scanf (" %99[^\n]%*c", surname) != 1) {
fprintf (stderr, "error: invalid input - surname\n");
return 1;
}
printf ("\nYour whole name is : %s %s\n", first_name, surname);
return 0;
}
Example Use/Output
$ ./bin/firstlast
What's your first name?: David
Hey David!
Enter surname name? optional (Y/N) Y
Enter your surname?: Rankin
Your whole name is : David Rankin
Look it over and let me know if you have any questions.
There are two problems here. Firstly you need to see what value is returned by the strcmp and secondly you must use the approprate hedder.
You must use:
#include <string.h>
Secondly, you must edit your if-else statement so it is like this:
if (strcmp(ch, "Y") == 0){
printf("What is your surname?\n");
scanf("%s", surname);
printf("Your whole name is %s %s", first_name, surname);
}
We do this because the strcmp function returns a negative value if ch is smaller than "Y", or a positive value if it is greater than "Y" and 0 if both strings are equal.
The problem is at the age part, the compiler does not give me any errors but when I run it it prints a random number for int age
printf("Enter your name:");
scanf(" %s",&name1);
int age;
printf("\n\nHow old are you?");
scanf(" %d",&age);
char gender;
printf("\n\nEnter your gender[Male/Female]:");
scanf(" %s",&gender);
char confirmation;
printf("Confirmation: Your name is %s , you are %d years old , and you are a %s.\n\nAnswer[Y/N]:",&name1,age,&gender);
Here is your problem.
char gender;
scanf(" %s",&gender);
gender is a char. That is, it only has memory for a 1 byte character. But you are using it as a string. You probably have the same problem for name1 since you are using & for that as well but can't be sure as you don't show that.
Change that to be something like:
char gender[8] // Enough to fit "Female" and terminating NULL
scanf("%7s", gender);
Extra note: scanf is a bit awkward to use to prevent buffer safety. May consider something like fgets with sscanf instead.
There is also dynamic allocation, where you now do not have to specify the amount of storage to use. Using the length modifier %m with the string type modifier s:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *name = NULL
char *gender = NULL;
int age;
printf("Enter your name: ");
scanf("%ms", &name);
printf("\nHow old are you? ");
scanf("%d", &age);
printf("\nEnter gender: ");
scanf(" %ms", &gender);
printf("\n%s %d %s\n", name, age, gender);
free(name); // free the memory
free(gender); //
return 0;
}
In the last couple of lines you will notice a several calls to free. This is because you are left with the responsiblility to free the memory allocated by scanf.
As pointed out by #Matt McNabb if you are on a non-posix compliant system, this will not work. You can use a in place of m, while including #define _GNU_SOURCE on the first line.
I am just learning C and making a basic "hello, NAME" program. I have got it working to read the user's input but it is output as numbers and not what they enter?
What am I doing wrong?
#include <stdio.h>
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%d", &name);
printf("Hi there, %d", name);
getchar();
return 0;
}
You use the wrong format specifier %d- you should use %s. Better still use fgets - scanf is not buffer safe.
Go through the documentations it should not be that difficult:
scanf and fgets
Sample code:
#include <stdio.h>
int main(void)
{
char name[20];
printf("Hello. What's your name?\n");
//scanf("%s", &name); - deprecated
fgets(name,20,stdin);
printf("Hi there, %s", name);
return 0;
}
Input:
The Name is Stackoverflow
Output:
Hello. What's your name?
Hi there, The Name is Stackov
#include <stdio.h>
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%s", name);
printf("Hi there, %s", name);
getchar();
return 0;
}
When we take the input as a string from the user, %s is used. And the address is given where the string to be stored.
scanf("%s",name);
printf("%s",name);
hear name give you the base address of array name. The value of name and &name would be equal but there is very much difference between them. name gives the base address of array and if you will calculate name+1 it will give you next address i.e. address of name[1] but if you perform &name+1, it will be next address to the whole array.
change your code to:
int main()
{
char name[20];
printf("Hello. What's your name?\n");
scanf("%s", &name);
printf("Hi there, %s", name);
getchar();
getch(); //To wait until you press a key and then exit the application
return 0;
}
This is because, %d is used for integer datatypes and %s and %c are used for string and character types