Simple char output from string - c

I am learning C and I simply wanted to output the first char of the string that the user inputs. Somehow it doesnt work? I also got no error message. This must be a really simple question, but I dont get it.
#include <stdio.h>
int main(void)
{
char input[200];
char test;
printf("Text input: ");
scanf("%s", input);
test = input[0];
printf("%s", test);
return 0;
}

You need to use %c to print a char. %s is for null-terminated strings, i.e. char arrays. The code below works fine for me.
#include <stdio.h>
int main() {
char input[200];
char test;
printf("Text input: ");
scanf("%s", input);
test = input[0];
printf("%c\n", test);
return 0;
}

Try this
#include <stdio.h>
int main() {
char input[200];
char test;
printf("Text input: ");
scanf("%s", input);
test = input[0];
printf("%c\n", test);
return 0;
}
This works. U need to use %c rather than %s to print characters

Related

How can I stop the input when I enter end

got this little problem, I made this code for my task, it should input strings and print it in revese, the loop should end when you enter end, but it doesnt end, I know this is not how you check strings but I don't know how to correct it. Thanks in advance for help.
#include <stdio.h>
#include <stdlib.h>
void reverse(char str[]){
int length;
for(length=strlen(str)-1; length >= 0; length--){
printf("%c",str[length]);
}
}
int main(void){
char str[]="";
while(str != "end"){
printf("\nEnter string: ");
scanf("%s", str);
reverse(str);
}
return 0;
}
you have many problems in your code :
when you write char str[]=""; this is will create a string of size = 1 only which will not accept any string you enter except for only one char , so you should do char str[50]; where 50 is the max expected length of the entered string.
it's not while(str != "end") it's , while(strcmp(str,"end") != 0) as you want to compare the strings itself not addresses
it's better to write scanf("%49s", str); than scanf("%s", str); just to make sure that the entered string will always fit in your array
in this line length = strlen(str)-1; , the strlen function return unsigned long long , so you should typecast that and write length = (int)strlen(str)-1; instead
with this all being said , this is the edited code :
#include <stdio.h>
#include <string.h>
void reverse(char str[]){
int length;
for(length = (int)strlen(str)-1; length >= 0; length--){
printf("%c",str[length]);
}
}
int main(void){
char str[50];
while(strcmp(str,"end") != 0){
printf("\nEnter string: ");
scanf("%49s", str);
reverse(str);
}
return 0;
}
and this is the output:
Enter string:abcd
dcba
Enter string:end
dne
Process finished with exit code 0

Why is not this array of arrays being printed correctly in C?

I have been working some time on the code below but for some reason there is no way I can print out correctly the chars array of an array after returning it and using it in the main function.
I cannot come up with any other things I could print in the code to check what is wrong. I do have checked other similar posts in the forum but I cannot spot any differences between the answers given there and how my code is written.
Does anyone spot anything wrong?
Many thanks in advance.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING 35
char **getWordsList(size_t *wordsNumber);
int main(){
int wordsNumber;
char **arrayOfArrays=getWordsList(&wordsNumber);
printf("WordsNumber is %d",wordsNumber);
printf("\nPrinting the resulting array of arrays: \n");
for (size_t indx=0; indx<wordsNumber; indx++){
printf("%s ", *(arrayOfArrays+indx)); //WHY ISNT THE STRING PRINTED CORRECTLY ?
}
free(*arrayOfArrays);
free(arrayOfArrays);
return 0;
}
char **getWordsList(size_t *wordsNumber){
printf("Please enter the number of words: ");
scanf("%zu",wordsNumber);
fflush(stdin);
char **wordsList=malloc(sizeof (char *)*(*wordsNumber));
if (wordsList!=NULL){
for (size_t indx=0; indx<*wordsNumber; indx++)
{
char inputWord [30];
printf("Please enter a word: ");
fgets(inputWord,sizeof(inputWord),stdin);
fflush(stdin);
printf("Word is %s",inputWord);
*(wordsList+indx)=malloc(MAX_STRING*sizeof(char));
if (*(wordsList+indx)){
*(wordsList+indx)=inputWord;
printf("Added array component is: %s\n",*(wordsList+indx));
}
}
return wordsList;}
else{
printf("Error in allocating memory for array of arrays");
}
}
Thanks to the help I got from the post comments, I was able to produce a working code. I am posting it so others who are struggling wih similar problems can benefit from it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING 35
char **getWordsList(size_t *wordsNumber);
int main(){
int wordsNumber;
char **answer=getWordsList(&wordsNumber);
printf("WordsNumber is %d",wordsNumber);
printf("\nChecking: \n");
for (size_t indx=0; indx<wordsNumber; indx++){
printf("%s ", answer[indx]);
free(answer[indx]);
}
free(answer);
return 0;
}
char **getWordsList(size_t *wordsNumber){
long wordsNumberFoo;
char wordsNumberStr [40];
char *wordsNumberPtr;
printf("Please enter the number of words: ");
fgets(wordsNumberStr, sizeof(wordsNumberStr), stdin);
wordsNumberFoo=strtol(wordsNumberStr, &wordsNumberPtr, 10);
*wordsNumber=(size_t)wordsNumberFoo;
char **wordsList=malloc(sizeof (char *)*(*wordsNumber));
if (wordsList!=NULL){
for (size_t indx=0; indx<*wordsNumber; indx++)
{
char inputWord [30];
printf("Please enter a word: ");
fgets(inputWord,sizeof(inputWord),stdin);
inputWord[strcspn(inputWord, "\n")] = 0;
printf("Word is %s\n",inputWord);
strncpy(*(wordsList+indx),inputWord, MAX_STRING);
printf("Added array component is: %s\n",*(wordsList+indx));
}
return wordsList;}
else{
printf("Error in allocating memory");
return NULL;
}
}

Command Flow in C, function call after printf

So I have this super simple C code here taking a user input and prints it out followed by a "T-Plus" while loop. In this case I chose a random name for testing "whoa", but the while loop is not called. My question is, why does the "T-Plus: %d\n" while loop print not be called after the printf() function?:
#include <stdio.h>
char getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
printf("%s", getString());
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char getString()
{
char name;
printf("Please a string name: \n");
scanf("%s", &name);
return name;
}
Now when I run it, this becomes the output:
$ ./namecount
Please a string name:
whoa
but the T-Plus: string does not get called.
I see two issues here:
1) In function getString() you are trying to read/scan a string in a char, you need memory to store the string and a terminating char, so you can use either of these two ways
Use a char array e.g. char name[50]; or
Use a char pointer and
allocate memory using malloc e.g.
char *p_name = malloc(sizeof(char)*50);
2) You are then trying to return this string which is stored in local variable (which would get destroyed as soon as function ends) so you should use the second approach (use malloc) and return the pointer.
So your code would look like:
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *p_name = getString();
printf("%s", p_name);
free(p_name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char *getString()
{
char *p_name = malloc(sizeof(char)*50);
printf("Please a string name: \n");
scanf("%s", p_name);
return p_name;
}
Above answer did not work, Okay so I've edited the code like this, it compiles fine. But raises a segmentation fault though.
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *name = getString();
printf("%s", name);
free(name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char * getString()
{
char *p_name[50];
printf("Please a string name: \n");
scanf("%49s", (char *) &p_name);
return *p_name;
}
When the program is run, it asks for your input but still raises a Segmentation fault (core dumped).

How do I use a string variable in the printf() function in c?

I am running the following c program:
#include <stdio.h>
int main() {
char str1;
printf("What is your name? ");
scanf("%s.", str1);
printf("Hi there %s.", str1);
return 0;
}
But this what it returns:
What is your name? Varun
Hi there (null).
Why does it say (null)? Please answer.
You have multiple mistakes here:
You use %s for a char variable.
You're not passing a pointer to scanf function. You're just passing a garbage value.
You introduced an undefined behavior. And you should have some compile-warnings that tells you that you have mistakes.
char str1; you have space for only 1 char , that's not much , try replacing with char str1[30]; and try again.
Try this instead:
#include <stdio.h>
int main() {
char str1[1000]; // <-- here are the changes
printf("What is your name? ");
scanf("%s.", str1);
printf("Hi there %s.", str1);
return 0;
}
To use strings in c, you need to create a char array with a specific size
char arr[1000]; // array of size 1000, it can contain a string of 1000 letters
then to fetch the string you have to use
scanf("%s", arr);
then to print it back use
printf("%s", arr);
#include <stdio.h>
#include <malloc.h>
int main() {
char *str;
str = (char *)malloc(sizeof(char) * 10);
printf("What is your name?");
scanf("%s", str);
printf("Hi there %s.", str);
return 0;
}
I think you should do like this, you should understand char and string.

how to reverse the integers between two strings with changing lower to upper & upper to case alphabets in c

I have an input string such as :"Hello 12345 WoRlD"
and I want output it as : "hELLO 54321 wOrLd"
1)here the lower case should be converted to upper and vice versa
2)reverse the integers between two strings
after executing it will only prints first string only and the rest of output vanishes
Here is what I have attempted so far
#include<stdio.h>
#include<string.h>
char* casechange(char *);
main()
{
char s[30],*p,*q;
int i,j;
printf("Enter string data:");
scanf("%s",s);
q=casechange(s);
printf("Manipulated string data:%s\n",s);
}
char* casechange(char *s)
{
int i,j=strlen(s)-1,num;
for(i=0;s[i];i++)
{
if(s[i]>='a'&&s[i]<='z')
{
s[i]-=32;
}
else if(s[i]>='A'&&s[i]<='Z')
{
s[i]+=32;
}
}
if(s[i]>='0'&&s[i]<='9'&&s[j]>='0'&&s[j]<='9')
//for(i=0;i<j;i++,j--)
//{
{
num=s[i];
s[i]=s[j];
s[j]=num;
}
//}
return s;
}
How can this be accomplished?
The problem with "after executing it will only prints first string only and the rest of output vanishes" is:
scanf("%s",s);
The scanf() '%s' format string tells scanf to read in a string, but only up to the first space. Hence, if you enter:
"Hello 12345 WoRlD"
The scanf("%s", s) will copy only "Hello" into 's'.
To fix this, change:
scanf("%s",s);
To this:
fgets(s, sizeof(s), stdin);
However, fgets() may leave a unwanted '\n' at the end of the string. The unwanted '\n' can be eliminated by inserting the following code after the fgets():
q=strchr(s,'\n');
if(q)
*q = '\0';
Then the output will be:
"hELLO 12345 wOrLd"
SPOILER ALERT!
See my version 'casechange()', which will also reverse the number.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* casechange(char *);
int main(){
char s[30];
printf("Enter string data:");
scanf("%29[^\n]",s);//%s : separated by white space
casechange(s);
printf("Manipulated string data:%s\n", s);
return 0;
}
char* casechange(char *s){
int i;
for(i=0;s[i];i++){
if(islower(s[i]))
s[i] = toupper(s[i]);
else if(isupper(s[i]))
s[i] = tolower(s[i]);
else if(isdigit(s[i])){
int j, n;
char num[30];
sscanf(&s[i], "%29[0123456789]%n", num, &n);
for(j=0;j<n;++j)
s[i+j] = num[n-j-1];
i+=n-1;
}
}
return s;
}
else if(isdigit(s[i])){
int j, n;
char num;
sscanf(&s[i], "%*[0123456789]%n", &n);
for(j=0;j<n/2;++j){
num = s[i+j];
s[i+j] = s[i+n-j-1];
s[i+n-j-1] = num;
}
i+=n-1;
}

Resources