stuck with spaces and arrays - c

I want to display a full name, but I can't enter more than two parts of a name. The program stuck when enter a name which has more characters than the number which array has. How can I solve this?
#include <stdio.h>
#include<stdlib.h>
int main(){
char x[25];
printf("Enter your name");
scanf("%s",x);
printf("Your name is %s", x);
return 0;
}
Thank You

I think this can help you. This program doesnt care how many characters, spaces you entered. It only displays first 24 characters and spaces. (1 for string terminator)
#include <stdio.h>
#include <stdlib.h>
int main(){
char x[25];
char *xx=x;
puts("Input Name");
fgets(xx,25,stdin);
puts(xx);
return 0;
}

Related

unable to give input everytime for char using do while loop

I am not able to give input every time. It is skipping in between and I can only give input at alternate times I have created a do while loop and trying to take input as char.
#include <stdio.h>
int main()
{
char gender;
do{
printf("Enter gender\n");
scanf("%c",&gender);
if(gender=='m')
printf("Male\n");
else
printf("Other\n");
}while(1);
}
The scanf() read the new line too as a character and assign it to next char value.
Thats why you can able to read alternatively.
So read a dummy character next to it solve this.
Try this and let me know
#include <stdio.h>
int main()
{
char gender,temp;
do{
printf("Enter gender\n");
scanf("%c%c",&gender,&temp);
if(gender=='m')
printf("Male\n");
else
printf("Other\n");
}while(1);
}

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

scanf fails to read a string in C [duplicate]

This question already has answers here:
Reading string from input with space character? [duplicate]
(13 answers)
Closed 4 years ago.
I have a simple C program as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[100],b[100];
char *ret;
printf("Enter the string\n");
scanf("%s",a);
printf("Enter the substring to be searched\n");
scanf("%s",b);
ret= strstr(a,b);
if(ret==NULL)
{
printf("Substring not found\n");
}
else
{
printf("Substring found \n");
}
}
When I execute the following program, scanf to read the string into b is not waiting for me to enter the substring and the print statement that prints the substring not found is being printed on the console. I tried to give %sand tried in the scanf statement and removed \n from the printf statements and nothing changed the way it executed the program. It would be great if someone solves this simple problem. Thanks in advance.
You can use scanf ("%[^\n]%*c", variable); with this scanf will read the whole line, instead of stopping when a space is reached.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[100];
char b[100];
char *ret;
printf("Enter the string\n");
scanf ("%[^\n]%*c", a);
printf("Enter the substring to be searched\n");
scanf ("%[^\n]%*c", b);
ret= strstr(a,b);
if(ret==NULL)
{
printf("Substring not found\n");
}
else
{
printf("Substring found \n");
}
}
Also you can use fgets
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[100];
char b[100];
char *ret;
printf("Enter the string\n");
fgets(a,100,stdin);//100 is the size of the string, you could use sizeof()
printf("Enter the substring to be searched\n");
fgets(b,100,stdin);//100 is the size of the string, you could use sizeof()
ret= strstr(a,b);
if(ret==NULL)
{
printf("Substring not found\n");
}
else
{
printf("Substring found \n");
}
}
try to use fgets instead of scanf, probably the reason is that the spaces are treated as delimiters, and the parts before the space are treated as a and the part right after the space will be treated as b. Therefore the programme did not prompt you for another input.
For your information: Reading string from input with space character?

Changing The Case of A Letter in C?

I'm trying to change the case of a letter entered by the user and store a lower case and a higher case version of the letter in variables. I've written the code below but it's having issues running. Anyone point out what's causing the problems?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
char CaseChange(character){
int lowerc, higherc;
if(isupper(character)){
lowerc = tolower(character);
printf("%s", lowerc);
}
else{
higherc = character;
printf("%s", higherc);
}
return;
}
int main(void){
char character;
printf("Enter a character: ");
scanf("%c", character);
CaseChange(character);
return 0;
}
There are two problems in your code:
printf("%s", ...) is meant for outputting strings (char* and const char*), not single characters. Use printf("%c", ...)
You forgot to #include <ctype.h>
Side-note: You don't have to check if a character is uppercase with isupper(x). tolower(x) will leave already-lowercase characters intact.

array of character in C

I have a question simple like that: Let user enter some words from keyboard,one word per line until a '.' (period) entered then print out result, for example:
Enter a word: word1
Enter a word: word2
Enter a word: .
You have entered 2 word(s):
word1
word2
OK here my try but when I run it said file has stopped working after let me enter first word
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char *word[50]; //each word has maximum 49 character
int i=0, number_of_word;
do
{
printf ("Enter a word: ");
scanf("%s", &word[i]);
i++;
}
while (word[i][0]!='.');
number_of_word =i;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++)
{
printf("%s\n", &word[i]);
}
return 0;
}
-----------------------------------------------------------------------
EDIT 1:
OK I try this, it worked but I am still looking for best way to declare an unknown size array of character string since I don't know neither how many word user may enter nor how many letter of each word, in C++ it may called dynamic allocation array, I have no idea how to do it in C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char word[20][50]; //array has maximum 20 words, each word maximum 50 character
int i=0, number_of_word;
do
{
printf ("Enter a word: ");
scanf("%s", word[i]);
i++;
}
while (word[i-1][0]!='.');
number_of_word =i-1;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++)
{
printf("Word %d is %s\n", i, word[i]);
}
return 0;
}
You are not assigning any memory to store the individual strings, so your program invokes undefined behaviour.
This:
char *word[50];
defines an array of 50 pointers, but no further storage.
And when you do this:
scanf("%s", &word[i]);
you're writing into the pointer array.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *word[50]; //each word has maximum 50 word
char enter_word[50];//maximum 49 character
int i=0, number_of_word;
while(1){
printf("Enter a word: ");
scanf("%49s", enter_word);
if(*enter_word == '.')break;
word[i++]=strdup(enter_word);
}
number_of_word = i;
printf ("You entered %d word(s):\n", number_of_word);
for (i=0; i<number_of_word; i++){
printf("%s\n", word[i]);
}
for(i=0;i<number_of_word; ++i)
free(word[i]);
return 0;
}
When you declare
char *word[50];
You have 50 char pointers pointing to random memory. What you want is something like this:
char word[50][50];
Note that you can have only 49 words (and the '.'), and each can have less than 50 characters (don't forget the \0, so a word with 50 chars will overflow).
And you will want to change your scanf call to something like:
scanf("%s", word[i]);
Note that you do not need the &, since word[i] is already a pointer.
char *word[50];
You have an array of 50 pointers. You want an array of 50 byte chunks. How many words do you want to read? If you know the maximum, you can allocate the space in advance. If you don't, you need something like a linked list of strings, to which you can append a new item when you read it.
Its your printf Call. Remember to add the end character \0 to the end of the word. Printf when printing strings prints everything in the char array till it reads an end character \0
BasicAlly... Hos should printf know how long the word is and when it should stop printing?(Right now it continues forever)
You've done nothing to allocate memory for the individual strings.
Char *word[50] just declares a pointer to one array of char pointers.
EDIT
I'll try to illustrate this here with some pseudo code...formatted code on a phone is nearly impossible :) Given a prior char * input[50]:
char * nextString;
bool entering=true;
do{
nextString =calloc(50);
// enter the string to nextString
if (nextString[0] != '.'){
input[i] = nextString;
i++;
} else{
entering=false;
}
}
}while(entering)
"char *word[50]" have done nothing to allocate the memory for the individual string.
you should allocate it by using the function of alloc
you just try to use "%[^\n]" place of "%s" in scanf().
because "%s" stores characters until it found first space in the string.
try this with your very first asked Program
May its help to you.

Resources