0

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

3 Answers 3

6

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;
}
5
  • is this the other way instead of using a for loop?
    – Jagr
    Nov 22, 2017 at 7:04
  • 1
    scanf with %s scans a string (without any whitespace or new line) to a char array. so you need not to scan each character using for loop. Yeah, this is perfect way instead of for loop.
    – Jay Joshi
    Nov 22, 2017 at 7:07
  • 5
    But wait, there's more. You also get a buffer overflow, absolutely free! Nov 22, 2017 at 7:08
  • 1
    Actually, you want to protect from buffer overrun with scanf("%20s", word)
    – wallyk
    Nov 22, 2017 at 7:09
  • 4
    You should always validate the return of scanf, e.g. if (scanf ("%19s", word) != 1) { /* handle error */ }. Otherwise you can have no confidence printf("%s\n", word); won't invoke Undefined Behavior. (@wallyk -- it's "%19s" instead of "%20s" -- that can exceed the array bounds by 1) Nov 22, 2017 at 7:17
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;
}
-3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.