Home > Software design >  How to receive a sentence from a user input in C?
How to receive a sentence from a user input in C?

Time:09-09

I'm trying to create a small program using C programming. Essentially while running in the console, the program should receive a sentence from a user.

Deliverables:

  1. I want to be able to ask users their name
  2. prompt the user to enter a write a short sentence
  3. output a user name and their sentence prompt
  4. when the user types into the text area and presses Enter, it will Submit.

**Not sure if I have to create an HTML file to connect my c file to the form for the submit action. Below is what I have made so far. Thank you!

#include <stdio.h>
  
int main()
{
  char word[100];
  char name;

  printf("what is your name? ");
      scanf("%c", &name);
    
  printf("Enter your sentence: ");
    
    scanf("%s", word);
    printf("Output : %s", word);
    return 0;
}

CodePudding user response:

In your code you have enterd %c in name but it will only accept one character of the entered string but instead of this if you will user %s then it will accept complete string untill whitespace character. So In order to accept complete string with whitespace character you have to write %[^\n] or %[^\n]s.

#include<stdio.h>
int main(){
char word[100], name[50];
printf("What is your name ?");
scanf("%[^\n]",name);
printf("Enter your statement : ");
scanf(" %[^\n]",word);
printf("Output : %s",word);
return 0;
}

Method : 2

If you want to use another method to accept user input as string you have to add include one library of c which is <String.h> and then you can use gets function to accept complete string from the user.

Code :-

#include<stdio.h>
#include<string.h>
int main(){
char word[100], name[50];
printf("What is your name ?");
gets(name);
printf("Enter your statement : ");
gets(word);
printf("Output : %s",word);
return 0;
}
  • Related