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.
Related
I want the string to be printed till character ('e') comes.
Code which I tried:-
#include <stdio.h>
int main() {
int a,i,x;
char b[10];
char ch;
//enter input string
for(i=0;i<10;i++)
scanf("%c",&b[i]);
for(i=0;i<10;i++)
if(b[i]!='e')
printf("%c",b[i]);
return 0;
}
Input:abcdefghij
Actual output:abcdfghij
Desired output:abcd
Question : Where am I wrong ? Will putting a break inside if block work here?
This is much cleaner if you want to use scanf.
#include <stdio.h>
int main()
{
char b[101];
scanf("%100s", b);
printf("%s\n", b);
return(0);
}
Or even better.
#include <stdio.h>
#define MAX_LENGTH 100
int main()
{
char b[MAX_LENGTH+1]; // add 1 for the terminating zero
scanf("%100s", b);
printf("%s\n", b);
return(0);
}
This one uses fgets to read the entire line.
#include <stdio.h>
#define MAX_LENGTH 100
int main()
{
char b[MAX_LENGTH];
fgets(b, MAX_LENGTH, stdin);
printf("%s", b);
return(0);
}
How to print a string till limit?
What code should do is use fgets().
Avoid using scanf(). Is is too easy to use wrong.
#include <stdio.h>
#include <string.h>
int main() {
char b[100];
if (fgets(b, sizeof b, stdin)) {
// If code needs to lop off the potential \n at the end
b[strcspn(b, "\n")] = '\0';
printf("%s\n", b);
}
return 0;
}
Advanced issues include how to handle excessively long input lines and error handling - not shown here.
Here is what you need to do
#include <stdio.h>
int main()
{
int a,i,x;
char b[10];
char ch;
//enter input string
for(i=0;i<10;i++)
{
scanf("%c",&b[i]);
}
for(i=0;i<10;i++)
{
if(b[i]=='e')
{
break;
}
}
return 0;
}
re
There are several mistakes!
If you are initializing your loops from 0 then you need to set the condition till i<100.
Change your format specifiers to %s.
Change your IF statement to if(b[i]!='\0').
#include <stdio.h>
int main()
{
int i;
char b[10];
for(i=0;i<10;i++)
{
scanf("%c",&b[i]);
}
for(i=0;i<10;i++)
{
if(b[i]=='e')
{
break;
}
printf("%c",b[i]);
}
return 0;
}
I’m trying to get the _strrev function to work but when I put my string into a function it doesn’t seem to work, just when I'm out of the function..
I’m getting so frustrated because I'm not getting anywhere with this..
Here's my code so far
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse(char *string) {
char *str, temp;
int begin = 0, end = 0;
char word[64];
int jaja = 0;
printf("Your string from the function is %s\n", string);
printf("%s\n", _strrev(&string)); //And why isnt this working
jaja = strlen(string);
printf("Your string has %d characters\n", jaja);
}
int main()
{
char *str;
scanf("%s", &str);
printf("%s\n", _strrev(&str)); //How come this works
reverse("Okay");
getchar();
return(0);
}
So I would love some guidance where my mistake is, I seriously cant find it.
According to MSDN The prototype for _strrev is
char *_strrev(
char *str
);
If you have a char *string you must call it like this :
printf("%s\n", _strrev(string));
In this case
printf("%s\n", _strrev(&string));
you are passing a char**
To answer the question you posted in your code comments:
int main()
{
char *str;
scanf("%s", &str);
printf("%s\n", _strrev(&str)); //How come this works
That works because you're lucky, as your call to scanf() places whatever it reads into the actual memory used for the pointer str, and you're not entering enough data to cause problems. Try entering a really long string when running this program and it won't work as well.
You need to actually have a char buffer to read data into, like this:
int main()
{
char str[256];
scanf("%s", str);
printf("%s\n", _strrev(str));
or
int main()
{
char *str = malloc( 256 );
scanf("%s", str);
printf("%s\n", _strrev(str));
And as pointed out in the comments to the question, you can still overrun your buffer.
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];
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');
The following code uses getchar() to accept a line of input.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *rawString = (char *)malloc(200*sizeof(char));
char *rawStringInitial = rawString;
char c;
c=getchar();
while(c!='\n')
{
*rawString=c;
rawString++;
c=getchar();
}
*rawString='\0';
printf("\n[%s]\n",rawStringInitial);
return(0);
}
While typing, if I press backspace, shouldn't it also be received by getchar() & stored in the rawString-pointed location? However the output simply shows the final string without any special characters. Could someone explain why?
Standard input is (usually) buffered; non-printing characters like backspace are handled by the terminal server, and library functions like getchar() will never see them.
If you need to read raw keystrokes, then you will need to use something outside of the C standard library.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void get_string(char *string);
void main(){
char *stringVar;
clrscr();
printf("Enter String : ");
get_string(stringVar);
printf("String Enter : %s",stringVar);
getch();
}
void get_string(char *string){
char press;int i=0;
do{
press=getch();
if(press!=8){
printf("%c",press);
string[i]=press;
i++;
}
else if(i>0){printf("\b%c\b",0);sting[i]=NULL;i--;}
}while(press!13);
}
This is Will Work.