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.
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 <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.
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
This question already has answers here:
Why is getchar() reading '\n' after a printf statement?
(3 answers)
Closed 9 years ago.
This is a newbie question. I am new to C programming. I have the following code which does not prompt for 'Name' Onece the 'Age' is entered, it bypass the 'Name section.
#include <stdio.h>
int main()
{
char name[30],ch;
int age;
printf("Enter age : ");
scanf("%d", &age);
int i=0;
printf("Enter name: ");
while((ch = getchar())!='\n')
{
name[i]=ch;
i++;
}
name[i]='\0';
printf("Name: %s\n",name);
printf("Age : %d\n", age);
return 0;
}
After reading first prompt it bypass the second prompt which is using getchar() function. But if I change the order of prompt to ask for 'Name' first and then 'Age' it works fine.
The working code.
#include <stdio.h>
int main()
{
char name[30],ch;
int age;
int i=0;
printf("Enter name: ");
while((ch = getchar())!='\n')
{
name[i]=ch;
i++;
}
name[i]='\0';
printf("Enter age : ");
scanf("%d", &age);
printf("Name: %s\n",name);
printf("Age : %d\n", age);
return 0;
}
My coding IDE is CodeBlock and my compiler is GNU C Compiler (mingw32-gcc.exe)
Please help me to breakthrough.
A few improvements/advices to the code in the question:
the type of the return value of getchar() is int, so the type of ch also should be int
you could (and should, I believe) use format %s to read the name, this is easier and the leading white spaces in the input stream would not be a problem
the user of the code could give a name which contains more than 30 characters, and this input could crash your program, so you should protect your code for this possibility. You have two options:
a. use format '%29s" to read the name
b. change the definition of name to char *name, read it by scanf("%ms", &name);, and call free(name); after you do not need it anymore
Here is an example, in which the name can be very long and can include spaces:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
char *name;
int age;
printf("Enter name: ");
scanf("%m[^\n]", &name);
printf("Enter age: ");
scanf("%d", &age);
printf("Name: %s\n", name);
printf("Age : %d\n", age);
free(name);
exit(EXIT_SUCCESS);
}
And here is a run of it:
$ ./a.out
Enter name: a very looooooooooooooooooooooooooooooooooooooooooooooong name
Enter age: 12
Name: a very looooooooooooooooooooooooooooooooooooooooooooooong name
Age : 12
In first code the \n character left behind by the scanf is read by getchar. This makes the condition (ch = getchar())!='\n' in while loop false and the loop body never get executed.
You need to consume that \n character which comes up to the buffer along with the age you entered on pressing Enter key.
Putting the statement
while(getchar()!='\n');
after the scanf will consume all of the newline characters.
Your second code is working fine because %d skips white-space characters unlike %c specifiers.
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;
}