Store & display user input in an array in C - c

I am trying to display and print a word from the user and store it into my array which is called
char word[20]
But I am having trouble. I know we use a "for loop" to scan it into the array but I keep going in circles and I believe the problem is with the i < 20.
I researched this and found that the answers to this are extremely experienced and I need a really basic way of doing it without the extra stuff. So all I want is to get word from the user, store it and print it onto the screen.
Can someone help without experienced code?
Code in C
char getWord(char word[]);
int main()
{
char word[20];
getWord(word);
return 0;
}
char getWord(char word[])
{
int i;
printf("Enter a word: ");
for (i = 0; i < 20; i++)
{
scanf(" %c", &word[i]);
}
return word;
}

All you want is
#include <stdio.h>
int main() {
char word[20];
scanf("%s", word); // Read and store
printf("%s\n", word); // Print
return 0;
}

You can use fgets and puts to read and write a string.
#include<stdio.h>
#define MAX 20
int main()
{
int ar[MAX], i, count;
fgets(ar, MAX, stdin); //it will accept whitespaces as well
puts(ar); //displaying entered string
return;
}

if you want to read via characters, ending character should be set to null character for it to be string.
char getWord(char word[]);
int main()
{
char word[20]
getWord(word);
printf("%s\n", word);
return 0;
}
char getWord(char word[])
{
int i;
char c;
printf("Enter a word: ");
for (i = 0; i < 19; i++)
{
scanf("%c", &c);
if ( c == '\n' )
break;
word[i]=c;
}
word[i]='\0';
return word;
}

Related

C: Fill array only with the size of scanfed string

After i put a name in the terminal and it is shorter, then 20 chars, it wants inputs until i have filled all the 20 positions in the array.
I know it is because of the for cycle i have there, but I don't know how else to fill that end of the array with nothing("").
In the array there is for example this "Helloworld\n123\n123"
Thank you for help in advance.
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
main(void) {
char name[NAME] = {""};
malloc(sizeof(name[NAME]));
printf("Choose your name: ");
for (int i = 0; i < NAME; i++) {
scanf("%c", &name[i]);
}
//Welcome and the name
printf("Welcome: ");
for (int i = 0; i < NAME; i++) {
printf("%c", name[i]);
}
return 0;
}
You need to stop reading at a newline (+should also check return codes).
A loop like:
size_t i=0;
for (; i < sizeof(name)-1; i++) {
if (1==(scanf("%c",&name[i]))){ if (name[i]=='\n') break; }
else if (feof(stdin)) break; //end of file?
else return perror("getchar"),1; //report error
}
name[i]='\0';
will achieve that (can also use getchar/getc/fgetc instead of scanf)
or you can use fgets:
if(NULL==fgets(name,sizeof(name),stdin)) return perror("fgets"),1;
//erase a possibly included newline at the end
//(won't be there if you pressed Ctrl+D twice rather than
//Enter to submit your input or if you're at the end of
//a stdin redirected from a file)
size_t len = strlen(name);
if(name[len-1]=='\n') name[len-1]='\0';
Whole program with both versions (in the if(0){...}else{...}) :
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(void) {
char name[NAME] = {""};
//malloc(sizeof(name[NAME])); //a useless memory leak; don't do this!
printf("Choose your name: ");
if(0){
if(NULL==fgets(name,sizeof(name),stdin)) return perror("fgets"),1;
size_t len = strlen(name);
if(name[len-1]=='\n') name[len-1]='\0';
}else{
size_t i=0;
for (; i < sizeof(name)-1; i++) {
if (1==(scanf("%c",&name[i]))){ if (name[i]=='\n') break; }
else if (feof(stdin)) break; //end of file?
else return perror("getchar"),1;
}
name[i]='\0';
}
//Welcome and the name
printf("Welcome: ");
for (int i = 0; i < NAME; i++) {
printf("%c", name[i]);
}
return 0;
}
If you have to use scanf and %c format:
char *readLineUsingCharAndScanf(char *buff, size_t size, FILE *fi)
{
char ch;
char *wrk = buff;
while(size-- && fscanf(fi, "%c", &ch) == 1 && ch != '\n' ) *wrk++ = ch;
*wrk = 0;
return buff;
}
void dumpString(const char *restrict str, size_t size)
{
while(*str && size--)
{
printf("%03d [0x%02x] - %s\n", *str, *str, (*str >= 32 & *str <= 127) ? (char[]){'\'', *str, '\'', 0} : "not printable");
str++;
}
}
int main(void)
{
char name[20];
dumpString(readLineUsingCharAndScanf(name, 19, stdin), 20);
}
https://godbolt.org/z/vWvP68TbW
scanf() is not the best tool for your purpose. Here is a simple and safe solution:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NAME 20
int main(void) {
char name[NAME];
int c;
size_t i;
printf("Enter your name: ");
i = 0;
while ((c = getchar()) != EOF && c != '\n') {
if (i < sizeof(name) - 1)
name[i++] = c;
}
name[i] = '\0';
//Welcome and the name
printf("Welcome: %s\n", name);
return 0;
}
If you must use scanf(), use this:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NAME 20
int main(void) {
char name[NAME];
char c;
size_t i;
printf("Enter your name: ");
i = 0;
while (scanf("%c", &c) == 1 && c != '\n') {
if (i < sizeof(name) - 1)
name[i++] = c;
}
name[i] = '\0';
//Welcome and the name
printf("Welcome: %s\n", name);
return 0;
}
Thank you everyone for answering. Unfortunately the first two answers are too complicated for me yet. And the third one was not working properly.
But I found the simplest answer. :) Many thanks
#include <stdio.h>
int main(void)
{
char name[20];
printf("Choose your name: ");
scanf("%[^\n]*c",name);
printf("My name is %s",name);
}
For your needs I would use scanf with the string conversion specifier %s. In this case, the input name would be read and stored character by character in the buffer until the whitespace would be read. Here is the code.
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char name[NAME] = {""};
malloc(sizeof(name[NAME]));
printf("Choose your name: ");
scanf("%s", &name);
printf("%s", &name);
return 0;
}

My result is 1 but the length of string i entered is longer

#include <stdio.h>
int length(char *point)
{
int n=0;
if (*point!='\0')
{
point++;
n++;
}
return n;
}
void main()
{
int m;
char *point;
char chars[80];
printf ("please enter a chars\n");
gets(chars);
point=chars;
m=length(chars);
printf("The length of the chars is %d.\n",m);
}
I want to ask why the "n" can't be added?
I think the problem is about the use of point,but i can't find it.
Thanks.
size_t length(const char *point)
{
size_t n = 0;
while (*point != '\0') // Need to loop to iterate through point
{
point++;
n++;
}
return n;
}
I would use it in the main like that :
int main(void)
{
char chars[80];
printf ("Please enter a chars\n");
scanf("%79s", chars);
// The 79 is there to limit the input to the size you allocated in chars[80]
// Thus avoiding buffer overflow
size_t m = length(chars);
printf("The length of the chars is %zu.\n",m);
return 0;
}
You forget to iterate through the string. You incremented the pointer but that's all. Also, I recommend using strlen() which does exactly what you intend to do.
Using strlen():
int main(void)
{
char chars[80];
printf ("Please enter a chars\n");
scanf("%79s", chars);
size_t m = strlen(chars);
printf("The length of the chars is %zu.\n", m);
return 0;
}
You don't have a loop inside your function length(). The if is only evaluated once.
Add (or replace the if with) a loop statement
/* loop */ {
if (*point!='\0') { /* ... */ }
}

I'm trying to make a string accept only letters and space BUT NO NUMBERS

This is what I theorized it should be but it seemed like it doesn't work.
HELP PLEAZEE
int main()
{
char input[50];
int i;
do{
printf("ENTER A CHARACTER:");
scanf("%s",&input);
if(isalpha(input)!=0){
printf("YOU INPUTTED A CHARACTER");
i++;
}else{
printf("INVALID INPUT\n");
}
}while(i!=1);
}
isalpha takes an integer as an argument.
You are giving a char array.
You should loop for the number of characters given in input[], if you want more than one character (hard to tell from this code).
This exits if you give exactly one character but keeps going if you give more than one:
#include <stdio.h>
#include <string.h>
int main()
{
char input[50];
int i = 0, j;
size_t len = 0;
do
{
printf("ENTER A CHARACTER:");
scanf("%s",&input);
len = strlen(input);
for(j = 0; j < len; j++) {
if(isalpha(input[j]))
{
i++;
printf("YOU INPUTTED A CHARACTER %d\n", i);
}
else
{
printf("INVALID INPUT\n");
break;
}
}
} while(i!=1);
}

Can printf print defined strings?

Is it possible to scan a character, pass it to a char array and then if a is defined as string to print that string? Below is the code, (which gets the warning "cast to pointer from integer of different size")
Thanks in advance
char *a = "alpha";
int main()
{
char *A[80];
char ch;
printf("enter message");
scanf(" %c", &ch);
A[0] = (char *) ch;
printf("%s\t", A[0]);
return 0;
}
What you want might be something like this.
#include <stdio.h>
/* word candidate list: terminated by NULL */
const char* a[] = {
"alpha",
NULL
};
int main(void)
{
char ch;
int i;
/* read input */
printf("enter message");
if (scanf(" %c", &ch) != 1)
{
puts("read error");
return 1;
}
/* search for matching word(s) */
for (i = 0; a[i] != NULL; i++)
{
/* if the first character of the word is what is scanned, print the word */
if (a[i][0] == ch)
{
printf("%s\t", a[i]);
}
}
return 0;
}
Here's what you probably meant to write:
int main()
{
char A[80];
char ch;
printf("enter message");
scanf(" %c", &ch);
A[0] = ch;
printf("%c\t", A[0]);
return 0;
}
You didn't declare you array A right, and when you print a char (A[0]), you should use %c in printf() function.
If you wanted to print it as an string (%s modifier), you need to NULL-terminate it, which means adding \0 at the end of the string.
If you want to create a string from a char and print it using "%s" then, you need to do something like below:
char *a = "alpha";
int main()
{
char A[80] = {0};
char ch;
printf("enter message");
scanf(" %c", &ch);
A[0] = ch;
printf("%s\t", A);
return 0;
}
The mistakes in your code were:
You were declaring an array of char pointers instead of an array of
char
You were assigning a char typecasted as char *
Your print statement was incorrect due to the declaration of char
array being wrong.
Please note that I have initialized the array A to 0, so that the string is automatically null terminated.
Based on your comment, the updated code for your expected solution:
char *a = "alpha";
int main()
{
char ch;
printf("enter message");
scanf(" %c", &ch);
if (ch == 'a')
printf("%s\t", a);
return 0;
}
Try this code, I'm now on mobile phone. I haven't tested it.
int main()
{
char A[80];
char ch;
printf("enter message");
A[0] = (char)fgetc(stdin);
printf("\n%c\n", A[0]);
return 0;
}

c - compiler, different errors?

i'm running this code on a macbook with xCode, and it runs flawlessly without any errors. However, when I try to compile and run the exact code on a Red Hat Linux server, I get a segmentation fault at line 25. I'm not sure why this is working for one machine, and not the other.
#include <stdio.h>
#include <string.h>
//Count the number of times the letter appears in the string
int count_letter(char str[], char * ch)
{
int i, num = 0;
for(i=0; i < strlen(str)-1; i++)
if(str[i] == *ch)
{
//printf("The character is %c", ch);
num++;
}
return num;
}
//Get the sentence and character to search for from the user
char * get_info(char * ch)
{
char *str;
//int i=0;
printf("Enter a sentence to search: ");
while((str[i++]=getchar())!='\n');
str[i]='\0';
printf("Enter a character to search for: ");
*ch=getchar();
return str;
}
//Get a sentence and character from the user and count the number
//of times the character is found in the sentence.
int main()
{
char *sentence;
char ch;
int num_letters;
sentence = get_info(&ch);
num_letters = count_letter(sentence, &ch);
printf("%c is found %d times.\n", ch, num_letters);
return 0;
}
Thank you
char *str;
You have not allocated any memory for it in get_info().
So first allocate memory for it.like
str= (char *)malloc(MAX_LEN*sizeof(char)); //MAX_LEN=define yourself what you want

Resources