why does my program not print out the final result? - c

why when i run this code to take in a string input by the user why does it not print out the final result ?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Function Declerations */
/* Global Variables */
char *text = NULL;
int size;
int main(){
/* Initializing Global Variables */
printf("enter a number limit for text: ");
scanf("%d", &size);
/* Initial memory allocation */
text = (char *) malloc(size * sizeof(char));
if(text != NULL){
printf("Enter some text: \n");
scanf("%s", &text);
// scanf(" ");
// gets(text);
printf("You inputed: %s", text);
}
free(text);
return 0;
}
/* Function Details */
in fact the end result looks like this
enter a number limit for text: 20
Enter some text:
jason

text is already a char *, so you don't have to pass &text to scanf, but only text.
scanf takes a pointer as argument in order to modify the pointed value, but if you pass a char ** as an argument, you will modify the pointer to the string instead of the pointed string

you just have to remove the address from &text because text is a pointer and the string always pointe to the first character.

Related

using malloc for char variable can not take input data character

I am trying to implement DMA for char variable. But I am unable to take input. I tried with all the possible cases I know:
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
But I can't even enter input data for the character variable ptr_name. I want to take input as "string with space" as input value. How to solve this problem?
And then how to print the entered name in the screen?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
ptr_name = (char*)malloc(name);
printf("Enter name: ");
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
scanf("%d", ...) does not consume the enter so the next scanf() gets an empty string.
you can use getchar() to consume the enter.
Also, you need to allocate additional byte for the zero at the end of the string / string terminator. See the + 1 in malloc().
As for your questions, your commented scanf() had & before argument 2 which isn't expected (char ** vs. char *) but other than that it will allow spaces in strings. puts() will print the entered name, alternatively you can modify the above printf() to print the name, e.g: printf("\n Your name is: %s", ptr_name);
Lastly, please consult Specifying the maximum string length to scanf dynamically in C (like "%*s" in printf) for dynamically limiting the input size, avoiding buffer overflow.
DISCLAIMER: The following is only "make it work" version of the program above and is not intended for real life use without appropriately checking return codes and limiting the input size:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
getchar();
ptr_name = (char*)malloc(name + 1);
printf("Enter name: ");
scanf("%[^\n]", ptr_name);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
if you want to get input with spaces you need to use getline():
getline(&buffer,&size,stdin);
here an example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int len;
printf("Enter number of characters for Name: ");
scanf("%d",&len);
ptr_name = (char*)malloc(len);
printf("Enter name: ");
getline(&ptr_name, &len, stdin);
printf("\n Your name is: %s", ptr_name);
free(ptr_name);
return 0;
}

How to show the result of written strings

I'm learning C Programming and I can't resolve this issue.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first;
printf("Write Down Your First Name!\n\n");
scanf("%s", &first);
int last;
printf("\nNow Write Your Sir Name!\n\n");
scanf("%s", &last);
printf("\nYour Full Name is %s\n\n");
system("pause");
return 0;
}
And I want to show the full name written.
Should I use void?
Thanks in advance
first and last should be of char array type instead of int type if you want to store characters into that.
int first; ---> char first[100]; /* define how many char you want in first*/
similarly
int last; --> char last[100];
And while scanning it you don't have to pass &
scanf("%s", first);
scanf("%s", last);
Want to print/show ?
printf("\nNow Write Your Sir Name! %s n\n", first);/* you missed to pass argument to printf */
printf("\nYour Full Name is %s\n\n",first);
How to join both ? Iterate last upto '\0' char and copy each char of last to end of first
int len = strlen(first);
first[len] = ' ';/* if needed, put space at the end of first */
for( i = 0, j = len + 1 ; last[i]!='\0;i++,j++) {
first[j] = last[i]; /* first should have enough space */
}
first[j] = '\0';
Now print it as
printf("\nYour Full Name is %s\n\n",first);

Passing String to Main from a function

#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

Just first alphabet is showing in the output.[char type]

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;
}

Storing Pieces of a String using Strtok

#include <stdio.h>
#include <math.h>
#include <string.h>
int main(void)
{
int menuswitch=1;
int amountofstudents;
int fname[50];
int lname[50];
int grade[50];
int i;
char studentinfo[100];
printf("Enter Amount of Students: ");
scanf("%d", &amountofstudents);
for (i=0;i<amountofstudents;i++)
{
gets(studentinfo);
strcpy(fname[i], strtok(studentinfo, " "));
strcpy(lname[i], strtok(NULL, " "));
strcpy(grade[i], strtok(NULL, " "));
}
Alright need a little using strtok. I am trying to store pieces of an input string to sort later. I was thinking of using strtok to break the string then placing each piece in the corresponding array. Yet, every time I try I get an error in Visual Studios saying Access Violation. Thanks for the help ahead of time
The error is
First-chance exception at 0x5120F7B3 (msvcr110d.dll) in Lab 2.exe: 0xC0000005: Access violation reading location 0x00000000.
Unhandled exception at 0x5120F7B3 (msvcr110d.dll) in Lab 2.exe: 0xC0000005: Access violation reading location 0x00000000.
The input would be
FirstName Lastname 80(Grade)
One major problem is that you try to copy into integer values and not strings. Change the
integer arrays to arrays of strings:
...
char fname[50][100];
char lname[50][100];
char grade[50][100];
...
You also have a problem with the gets function (besides it being obseleted and should not be used), namely that the previous scanf doesn't remove the newline from the input buffer so the first gets call will see this empty newline and give you an empty line (which you do not check for).
This is simply solved by telling scanf to discard trailing whitespace by adding a space in the format string after the "%d":
scanf("%d ", &amountofstudents);
/* ^ */
/* | */
/* Note space */
Instead of gets, you should be using fgets:
fgets(studentinfo, sizeof(studentinfo), stdin);
And finally, always check for errors!
a potential issue is the scanf/gets combo. use instead fgets() and convert when appropriate to integer using atoi() it is also good to do a sanity check on what is returned from strtok (it is never good to assume anything about input)
char* token = strtok(studentinfo, " ");
if ( strlen(token) < sizeof(fname[i]) )
{
strcpy(fname[i], token);
...
you have also declared your strings as integer arrays, they should be char
e.g. char fname[50];
The problem you have is that you have declared three variables (fname, lname, and grade) as char[] (arrays) (well, that is the type you meant to use), but you want to prompt for and keep around a bunch of students information. And you later try to copy from strtok() into what you want to be a char[], but since you dereferenced fname[i] (lname[i], grade[i]), they are of type char, rather than char[].
You will need stdlib.h for exit,
#include <stdio.h>
#include <stdlib.h> //for exit
#include <string.h>
//#include <math.h> //you don't need this, yet
#define STUDLIMIT (100)
You can either create an array of fname[], lname[], grade[], (see here: http://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html),
int main(void)
{
//int menuswitch=1; //you aren't using this
int amountofstudents;
char studentinfo[100];
char fname[STUDLIMIT][50];
char lname[STUDLIMIT][50];
char grade[STUDLIMIT][50];
int ndx;
printf("Enter Amount of Students: ");
if( (fscanf(stdin,"%d ", &amountofstudents)<=0)
|| (amountofstudents<1) || (amountofstudents>STUDLIMIT) )
{
printf("need %d to %d studends\n",1,STUDLIMIT); exit(0);
}
for (ndx=0;ndx<amountofstudents;ndx++)
{
printf("Student: "); fflush(stdout);
fgets(studentinfo,sizeof(studentinfo),stdin);
strcpy(fname[ndx], strtok(studentinfo, " "));
strcpy(lname[ndx], strtok(NULL, " "));
strcpy(grade[ndx], strtok(NULL, " "));
}
}
Or you can create a struct(ure) to hold the entered student information, and instantiate an array of these student records, one for each student you enter and store,
typedef struct student
{
char fname[50];
char lname[50];
char grade[50];
} StudentObj;
int StudentCopy(StudentObj*sp,char*fname,char*lname,char*grade)
{
if(!sp || !fname || !lname || !grade ) return -1;
strcpy(sp->fname, fname);
strcpy(sp->fname, lname);
strcpy(sp->fname, grade);
}
StudentObj students[STUDLIMIT];
int main(void)
{
//int menuswitch=1; //you aren't using this
int amountofstudents;
char studentinfo[100];
char fname[50];
char lname[50];
char grade[50];
int ndx;
printf("Enter Amount of Students: ");
if( (fscanf(stdin,"%d ",&amountofstudents)<=0)
|| (amountofstudents<1) || (amountofstudents>STUDLIMIT) )
{
printf("need %d to %d studends\n",1,STUDLIMIT); exit(0);
}
for (ndx=0;ndx<amountofstudents;ndx++)
{
printf("Student: "); fflush(stdout);
fgets(studentinfo,sizeof(studentinfo),stdin);
strcpy(fname, strtok(studentinfo, " "));
strcpy(lname, strtok(NULL, " "));
strcpy(grade, strtok(NULL, " \n\r"));
StudentCopy(&(students[ndx]),fname,lname,grade);
}
}

Resources