How can I read a string in c? [duplicate] - c

This question already has answers here:
How to read string from keyboard using C?
(6 answers)
Closed 9 years ago.
I use this code, but it's not working.
#include <stdio.h>
#include <string.h>
int main() {
char c, *strx = 0;
c = getchar();
while(c != '\n') {
strx = strcat(strx, &c);
c = getchar();
}
printf("%s\n", *strx);
return 0;
}
How can I put a word into a string?

Change
char *strx = 0
to
char strx [256];
For example:
#include <stdio.h>
#include <string.h>
int main()
{
char c, strx[256] = "";
int i = 0;
c = getchar();
while (c != '\n') {
strx[i++] = c;
c = getchar();
}
printf("%s\n", strx);
return 0;
}

You need to allocate space for strx (here on the stack, you can also you malloc)
#include <stdio.h>
#include <string.h>
int main()
{
char c, strx[100] = "";
int i = 0;
c = getchar();
while (c != '\n') {
strx[i++] = c;
if (i == 99)
break;
c = getchar();
}
strx[i] = '\0';
printf("%s\n", strx);
return 0;
}
strcat doesn't work because it expects a null char at the end but it will probably find garbage after the char.
More simply, you can use scanf:
#include <stdio.h>
#include <string.h>
int main()
{
char strx[100] = "";
scanf("%99s", strx);
printf("%s\n", strx);
return 0;
}

Related

Unexpected result after printing a string in c [duplicate]

This question already has answers here:
Why does fgetc() return int instead of char?
(2 answers)
Closed 1 year ago.
The code is -
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *filevar;
filevar = fopen("file", "r");
char copy [100];
int i = 0;
while(1)
{
char ch = fgetc(filevar);
if(ch==EOF)
{
break;
}
copy[i] = ch;
i++;
}
printf("\n%s", copy);
fclose(filevar);
return 0;
}
When I run it the out put I get is
textblablaâ– a
file content is -
textblabla
Changing the file content changes the random charecters at end
Two main issues.
ch has to be int
You do not null character terminate the string
int ch = fgetc(filevar);
if(ch==EOF)
{
copy[i] = 0;
break;
}
copy[i] = ch;
i++;

Dynamically allocate string to contain user input in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char* a;
scanf("%s",a);
printf("%s", a);
free(a);
return 0;
}
My question is dynamic allocation without static declaration.
I want to do dynamic assignment with just in the input statement.
Internal code or Not by a static declaration...
However, dynamic allocation is not possible with the above input this code.
Is there any other way?
By not touching the inner code or making static declarations.
You could use realloc from <stdlib.h> to achieve it.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
fputs("Input: ", stdout);
char *str = malloc(1);
int c, i;
for (i = 0; (c = fgetc(stdin)) != '\n' && c != EOF; ++i) {
str[i] = c;
str = realloc(str, i + 2);
}
str[i] = '\0';
printf("Output: %s\n", str);
free(str);
return EXIT_SUCCESS;
}
But I would not advise you to do that, because it can be expensive depending on the implementation. Instead I would just create a string with fixed size and prevent a buffer overflow.
char str[20];
scanf("%19s", str);
Or using fgets:
char str[20];
fgets(str, 20, stdin);

How do I check if a string contains a certain character?

I'm fairly new to C programming, how would I be able to check that a string contains a certain character for instance, if we had:
void main(int argc, char* argv[]){
char checkThisLineForExclamation[20] = "Hi, I'm odd!"
int exclamationCheck;
}
So with this, how would I set exclamationCheck with a 1 if "!" is present and 0 if it's not? Many thanks for any assistance given.
By using strchr(), like this for example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Hi, I'm odd!";
int exclamationCheck = 0;
if(strchr(str, '!') != NULL)
{
exclamationCheck = 1;
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}
Output:
exclamationCheck = 1
If you are looking for a laconic one liner, then you could follow #melpomene's approach:
int exclamationCheck = strchr(str, '!') != NULL;
If you are not allowed to use methods from the C String Library, then, as #SomeProgrammerDude suggested, you could simply iterate over the string, and if any character is the exclamation mark, as demonstrated in this example:
#include <stdio.h>
int main(void)
{
char str[] = "Hi, I'm odd";
int exclamationCheck = 0;
for(int i = 0; str[i] != '\0'; ++i)
{
if(str[i] == '!')
{
exclamationCheck = 1;
break;
}
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}
Output:
exclamationCheck = 0
Notice that you could break the loop when at least one exclamation mark is found, so that you don't need to iterate over the whole string.
PS: What should main() return in C and C++? int, not void.
You can use plain search for ! character with
Code
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Hi, I'm odd!";
int exclamationCheck = 0;
int i=0;
while (str[i]!='\0'){
if (str[i]=='!'){
exclamationCheck = 1;
break;
}
i++;
}
printf("exclamationCheck = %d\n", exclamationCheck);
return 0;
}

segmentation fault in c about using malloc, and char array pointer

im trying to make a program which reads what we wrote without concerning the memory, and print out what we wrote!
but it goes to segmentation fault (core dump)
#include <stdio.h>
#include <string.h>
int isdigit(char c);
int main()
{
char *input
int length;
printf("Number or Letter\n");
gets(input);
input = (char*)malloc(sizeof(char)*strlen(input));
printf(input[0]);
return 0;
}
To read in an arbitrary long input string, you must use some kind of memory re-allocation when the input string grows beyond the already allocated memory. For instance you could use realloc like this:
#include <stdio.h>
#include <stdlib.h>
#define INCREASE 32
int main(void) {
int c;
int allocated = INCREASE;
int used = 1;
char* in = malloc(allocated*sizeof(char));
if (!in) exit(1);
*in = '\0';
while((c = fgetc(stdin)) != EOF && c != '\n')
{
if (used > (allocated-1))
{
// printf("Realloc\n");
allocated += INCREASE;
char* t = realloc(in, allocated);
if (t)
{
in = t;
}
else
{
free(in);
exit(1);
}
}
in[used-1] = c;
in[used] = '\0';
++used;
}
printf("%s\n", in);
free(in);
return 0;
}

I need to read a file until "over" is encountered [duplicate]

This question already has an answer here:
C: How to compare two strings? [duplicate]
(1 answer)
Closed 9 years ago.
I have trouble reading a file until a word is encountered, this is what I have done but I don't think the if statement allows strings to be written within them
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int i;
char buffer[100];
FILE *fptr = fopen("testing.txt", "r");
if(fptr != NULL)
printf("file opened successfully\n");
else {
printf("file error occured\n");
printf("terminating program...\n");
return 0;
}
while (fgets(buffer, 100,fptr))
{
if(buffer != "over") {
printf("%s ", buffer);
}
else
return 0;
}
}
When you do
if(buffer != "over")
you compare two pointers, the pointer to buffer and the pointer to the string literal "over". Those pointers will never be the same.
To compare strings in C you have to use the strcmp function.
For comparing string you need to use strcmp() function. You can't do directly by if(buffer != "over"). It compares pointers instead of stings.
#include <stdio.h>
#include <string.h>
int isEndWith(const char *string, const char *word){
int len = strlen(string);
int lenw = strlen(word);
if(len >= lenw)
return strncmp(string + len - lenw, word, lenw)==0;//or use strcmp
else
return 0;
}
int main(void){
char str1[] = "how are you over i am busy over\n";
char str2[] = "how are you over i am busy over\n";
char *p;
if(p=strchr(str1, '\n'))
*p = '\0';//chomp \n
if(!isEndWith(str1, "over"))//check case end string
printf("%s", str1);
else {
int len = strlen(str1);
str1[len - 4] = '\0';// 4 : strlen("over");
printf("%s\n", str1);//print "how are you over i am busy \n"
}
if(p=strstr(str2, "over"))//check case contain string
*p = '\0';
printf("%s\n", str2);//print "how are you \n"
return 0;
}

Resources