This question already has answers here:
How to read unlimited characters in C
(3 answers)
Closed 8 years ago.
I am working on a project where I have to take input from a user in the terminal in c until they input quit then I end the program. I realized I cant do this:
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv){
char *i;
while(1){
scanf("%s", i);
/*do my program here*/
myMethod(i);
}
}
So my question is how can I go about taking this coninuous user input? Can I do it with loops or what else can I do?
First you have to allocate space for the string you are reading, this is normally done with a char array with the size of a macro. char i[BUFFER_SIZE] Then you read data into your buffer,fgets might be better than scanf for that. Finally you check your exit case, a strcmp with "quit".
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE BUFSIZ /* or some other number */
int main(int argc, const char **argv) {
char i[BUFFER_SIZE];
fgets(i, BUFSIZ, stdin);
while (strcmp(i, "quit\n") != 0) {
myMethod(i);
fgets(i, BUFSIZ, stdin);
}
}
Strings obtained with fgets are gurenteed null terminated
scanf() will return number of elements successfully read I will make use of it like below
#include<stdio.h>
#include<string.h>
int main()
{
int a[20];
int i=0;
printf("Keep entering numbers and when you are done press some character\n");
while((scanf("%d",&a[i])) == 1)
{
printf("%d\n",a[i]);
i++;
}
printf("User has ended giving inputs\n");
return 0;
}
You can use a do while loop:
do
{
// prompts the user
}
while (valueGiven != "quit");
using do-while loop.
char *i = null;
char ch = 'a';/
do{
scanf("%s", &i);
/*do my program here*/
myMethod(i);
printf("Do you want to continues.. y/n");
ch = getchar();
}while(ch != 'q');
Related
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
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Why doesn't my program take input inspite of the fgets part? Any other suggestions are welcome
(1 answer)
Using scanf and fgets in the same program?
(4 answers)
fgets doesn't work after scanf [duplicate]
(7 answers)
Closed 1 year ago.
I atentionally keep optional details for a best undersanding. say we want to store a string in a variable of char* :
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char * s;
int n;
do{
printf("string's length: ");
scanf("%d", &n);
}while(n<=0);
s = (char *) malloc((n+1) * sizeof(char));
if(s!=NULL){
printf("enter a string (length <= %d): ", n);
gets(s);
puts(s);
free(s);
}
puts("end of programme.\n");
return 0;
}
in this answer it says :
If you were to set s to point to a preexisting array or if you used malloc to allocate space, then you can write to it successfully.
so, despite all that, why the call to gets still doesn't success? how can we explain this behavior ?
The problem is that gets read the the buffer until a line break (\n), when you input a number, you press enter to confirm it, and the \n goes to the buffer. The gets read it and assume that's what you want. You need to throwaway the line breaker before call gets.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char * s;
int n;
do{
printf("string's length: ");
scanf("%d", &n);
}while(n<=0);
scanf("%*c"); // throwaway a character, in this case, the line breaker
s = (char *) malloc((n+1) * sizeof(char));
if(s!=NULL){
printf("enter a string (length <= %d): ", n);
gets(s);
puts(s);
free(s);
}
puts("end of programme.\n");
return 0;
}
#include <stdio.h>
#include <conio.h>
#define max 100
void compare(char *name,char* input);
int main()
{
int i=0;
char name[max]="santosh";
char input[max];
printf("enter the password\n");
while((input[i]=getchar())!='\n'){
i++;
}
input[i]='\0';
compare(name,input);
return 0;
}
void compare(char *name,char* input){
while((*name==*input)&&(*name!='\0'&&*input != '\0')){
*name++;
*input++;
}
if(*name=='\0'&&*input=='\0')
printf("Correct Password");
else
printf("Incorrect Password");
}
This Program is getting crashed in vs code but when I use getchar() instead of getch() or getche() all is working fine.
Why it is not working with getch() and how it will run as I want user to insert a password and thus want to use getch() not getchar().
First of all #define max generates a warning "macro redefinition", so change that.
The second problem is that getch() and getche do not convert the Enter key to 'newline' \n but to 'return' \r
The third problem is that instead of incrementing the pointers, you are incrementing what they point to.
Here is the corrected code:
#include <stdio.h>
#include <conio.h>
#define MAXX 100 // fixed macro name collision
void compare(char *name, char* input);
int main(void) // corrected definition
{
int i = 0;
char name[MAXX] = "santosh";
char input[MAXX];
printf("enter the password\n");
while((input[i] = getche()) != '\r') { // fixed '\n' check
i++;
}
input[i] = '\0';
compare(name, input);
return 0;
}
void compare(char *name,char* input){
while(*name == *input && *name != '\0' && *input != '\0') {
name++; // fixed pointer increment
input++; // fixed pointer increment
}
if(*name == '\0' && *input == '\0')
printf("Correct Password\n");
else
printf("Incorrect Password\n");
}
Finally you should also check i does not exceed the array bounds. The strings seem long enough, but not for players who try to break the program.
I wrote a simple program to read a string.
void main()
{
char *str; /*didn't allocate memory*/
scanf(" %s",str);
printf("%s",str);
}
But it is causing a segmentation fault. Whereas the next one isn't.
void main()
{
char *str;
scanf(" %c",str);
printf("%c\n",str);
}
Would someone mind to clarify how actually this works?
You string isn't allocated. which mean you are writing somewhere you didn't ask for.
however what you can do is:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char c;
while (scanf("%c",&c) && c != '\n')
printf("%c",c);
printf("\n");
return 0;
}
It will read every characters you send in input until you press return.
I am making a text based game, and i am having a big problem with input. Here is a small example of my problem code.
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
}
return 0;
}
So, if you compile/run this, and type in 'abc', it will just take each one, and send it through the loop. What I need it to do is only take the very first character that someone types in, no matter how many they do type in.
And, PS: I have tried it this way, and it does the same thing:
#include <stdio.h>
#include <stdlib.h>
char c[2];
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
scanf("%1s", c);
printf("\nYour input: %c\n", c[0]);
sleep(1);
system("clear");
}
return 0;
}
EDIT: It also adds a space to what ever you type in, I assume it is a \0, but im not sure. Thanks!
When you use scanf, enter a string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character. The string or character by character gets consumed by the scanf but the newline remains in the input buffer, unless you consume that too.
getchar(), on the other hand will not wait for ENTER key, it would read character by character, then your logic.
I think you can add 1 more line to read all the characters that come after the first one until there is a newline character (i.e. the user presses Enter):
while (getchar() != '\n');
Adding to your example, it would be like this:
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
while (getchar() != '\n');
}
return 0;
}
Use getch() which does not wait for a newline.
What i think you look for is something like this code, to save very first character, you can also check if c == '\n' to continue your operation, but i dont know what you want after saving very first character:
int i,c;
char save;
for ( i = 0;(c=getchar())!= EOF ; i++)
{
if ( i == 0)
save = c;
}
You can use fgets(), and extract its first character, like...
char ch[2], c;
fgets(ch, 2, stdin);
c = ch[0];