I wanted to make a simple program in C that will in while loop get 10 strings user inputs and store them to file food.txt. But there is problem whenever I try to store again user input to variable inputFood. It also send error at 'strcpy(&allFood, inputFood);' Thread 1: Signal SIGABRT. Can anyone help please?
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main() {
int i = 0;
printf("Hello World!\n");
char * inputFood;
char allFood = {0};
FILE * fPointer;
fPointer = fopen("/Users/Antonio/Desktop/food.txt", "a");
while (i < 10){
i = i + 1;
scanf("%s", inputFood);
strcpy(&allFood, inputFood);
}
fputs(&allFood, fPointer);
fclose(fPointer);
}
Allocate memory for inputFood, for example 100 chars:
inputFood = malloc(100);
and make allFood an array, not a char:
char allFood[1000];
Because of that you will need to use strcat indstead of strcpy like this:
strcat(allFood, inputFood);
And scan the input food like this:
scanf("%99s", inputFood);
you have to change many things in your program
1)allocate memory for inputFood
inputFood = malloc(100*sizeof(char));
2)as allFood is already a pointer, dont use & in strcpy, and usestrcat`.
strcat(allFood, inputFood);
same goes for fputs
fputs(allFood, fPointer);
3) make allFood a character array, as strcpy and fputs uses character pointers.
char allFood[1000];
char * inputFood;
You need first allocate memory for it. use malloc/calloc memory allocation.
And and
strcpy use for copy string not char.Also use fgets instead scanf to overcome buffer overflow issue.
Try something like this:
char inputFood[1024];
char allFood[1024];
while (i < 10){
i = i + 1;
fgets(inputFood, sizeof(inputFood), stdin);
if((strlen(allFood)+strlen(inputFood))<1024)
strncat(allFood, inputFood,strlen(inputFood));
}
Related
hey guys i have looked around for a solution and tried everything i can think of im new to pointers and dynamic strings and i could really do with some help with problem. im currently learning c and i need to get the user to input a dynamic size for the string length . i need to make it so the users input can not be bigger then 100 . here's where i am at currently . i have the code booting but if i try set the size to let's say 5 i can still input way more chars into the string. cheers really appreciate any help .
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
int maxSize = 100;
char *name = (char*) malloc (maxSize * sizeof (char));
int n;
char text1[]= ("input string size\n");
printf ("your string lenght is %d\n", strlen(name));
//getting size
n=intPrintScanner(text1);
printf ("your size is %d\n",n);
name = realloc (name, sizeof (char) * n);
//printing results
printf ("your string lenght is %d\n",strlen (name));
scanf("%s", name);
printf("your string is %s",name);
free(name);
fflush(stdin);
printf("press any key to close");
getchar();
return (0);
}
Bugs:
You never assign any data to name so it just contains garbage. You can't use strlen on it before you have stored valid data there either. You can store a string inside name by for example using strcpy.
When using realloc, there's no guarantee that the old pointer is the same as the returned pointer. Also, you need error handling. Implement it like this instead:
char* tmp = realloc (name, n);
if(tmp == NULL)
{
/* actual error handling here in case realloc fails */ }
}
name = tmp; // assign pointer to the new area only if allocation succeeded
fflush(stdin); is not well-defined, never use fflush on input streams. Instead you should discard unwanted line feed characters from stdin - which could be as trivial as an extra getchar() call just after reading something. Check out How to read / parse input in C? The FAQ for lots of general good advise regarding how to take input from stdin.
Cosmetic/style:
No need for parenthesis here: char text1[]= ("input string size\n");. All it achieves it to make the code look strange.
The correct form of main is int main (void). The int main() is obsolete style.
There is no need to wrap the expression passed to return in a parenthesis.
There is never a need to multiply something with sizeof (char), since sizeof (char) is by definition always 1 no matter system.
There is no need to cast the result of malloc.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
char* read_until(int fd, char end) {
int i = 0, size;
char c = '\0';
char* string = (char*)malloc(sizeof(char));
while (1) {
size = read(fd, &c, sizeof(char));
if (c != end && size > 0) {
string = (char*)realloc(string, sizeof(char) * (i + 2));
string[i++] = c;
} else {
break;
}
}
string[i] = '\0';
return string;
}
int main()
{
char *name;
int correct=0;
do{
write(1,"Put a name: ",strlen("Put a name: "));
name = read_until(STDIN_FILENO,'\n');
if(strlen(name) > 99){
write(1,"Error\n",strlen("Error\n"));
}else{
correct=1;
}
}while(correct != 1);
write(1,name,strlen(name));
free(name);
}
Try using write and read instead of printf and scanf, it is better for allocating dynamic memory, read and try to understand the read_until function, there are better ways to do main.
I want to have an array of strings and the user to enter a string at a time. The program should either end if the the array is full or when the user skips an input (so the string would be equal to "\n".
Problem is that I have to dynamically allocate memory for each of these strings and I cant find a way to do that efficiently.
Excuse my English on this one but the array should be an array of pointers to char (for example char *pin[MAX])
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 5
int main()
{
char *pin[MAX];
char s[] = "";
int n = 0;
while(s != "\n"){
printf("Enter a string: ");
gets(s);
pin[n] = malloc(sizeof(char)*strlen(s));
strcpy(pin[n], s);
n++;
if(n = MAX - 1) break;
}
for(int i = 0; i < MAX; i++){
printf("%s ", *pin[i]);
}
return 0;
}
Take input with fgets and store it in a temporary buffer (128 or 256 bytes large etc).
Call strlen on the read string stored in this buffer to see how much to allocate.
Allocate memory with malloc for pointer pin[n] and strcpy the string there.
NOTE:
char *s; ... while(s != is nonsense since s has not been initialized.
s != "\n" is nonsense since that's not how you compare strings in C.
pin[n] == &s; is nonsense because it's just random stuff typed out without the programmer knowing why. Programming by trial & error doesn't work.
In general you need to study arrays and pointers before strings.
At the end of this question you will find a piece of code that I am trying to write to read a file called words.txt with the following strings:
uno dos tres cuatro cinco seis siete ocho nueve diez
The aim of the code is to be able to store the strings in a two-dimensional array with dynamic memory allocation. This means it would need to work with any file that has strings.
I would need to check:
Why the code is not working.
How can I make it so that it stores whatever number of words the file has.
Thank you very much guys!
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
int main()
{
char c, *mystring[20];
int i = 0;
FILE *fich;
setlocale(LC_CTYPE,"spanish");
identifica();
fich = fopen("words.txt", "r");
do
{
mystring[i] = malloc (20 * sizeof(char));
fscanf("%s", mystring[i]);
printf ("%s", mystring[i]);
}
while ((c=fgetc(fich))!=EOF);
return 0;
}
You forgot to pass fich to fscanf(). (This is why your code won't work)
Checking if fscanf() is successful should be performed.
You can use realloc() for dynamic re-allocation.
You should increment i for storeing all strings.
Maximum length of string to read should be specified to avoid buffer overrun.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
int main()
{
char **mystring = NULL;
int i = 0;
FILE *fich;
setlocale(LC_CTYPE,"spanish");
identifica();
fich = fopen("words.txt", "r");
for (;;)
{
char* next = malloc (20 * sizeof(char));
if (fscanf(fich, "%19s", next) == 1)
{
printf ("%s", next);
mystring = realloc(mystring, sizeof(*mystring) * (i + 1));
mystring[i] = next;
i++;
}
else
{
free(next);
break;
}
}
return 0;
}
I have this program that's supposed to be a 'chat simulator', the only thing it's supposed to do now is replying 'Hello!' when the user types 'Hello'.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
int main()
{
printf("Chat simulator!\n");
do {
char x;
printf("[User1] ");
scanf("%s",&x);
if (strcmp (x,"Hello") == 0)
{
Sleep(1500);
printf("[User2] Hello!\n");
}
else {}
} while(1);
}
I know that strcmp is only for const char *, not a single char, and that's the problem here, but I couldn't find any other solution for this, since I need to use char x in scanf, so it can't be a const char *. Also it may be possible that I'm using strcmp wrong.
Code:Blocks warning:
passing argument 1 of 'strcmp' makes pointer from integer without a cast*
expected 'const char *' but argument is of type 'char'*
Edit:
So I changed the char to char[16] as #robin.koch told me, and it's all working as it should. Thanks!
You cannot compare a string with a char with strcmp, but it is easy to do by hand:
int samechar(const char *str, char c) {
return *str == c && (c == '\0' || str[1] == '\0');
}
The above function however is not what you need for you problem:
You should read a string from the user, not a single char.
scanf() needs a pointer to a char array for the conversion specifier %s.
Furthermore you should specify the maximum number of characters to store into the this array to avoid potential a buffer overflow.
Finally, scanf() will only read a single word. You probably want to read a full line from the user. Use fgets() for this.
Here is a modified version:
#include <stdio.h>
#include <string.h>
int main(void) {
printf("Chat simulator!\n");
for (;;) {
char buf[100];
printf("[User1] ");
if (!fgets(buf, sizeof buf, stdin))
break;
buf[strcspn(buf, "\n")] = '\0'; /* strip the newline if present */
if (strcmp(buf, "Hello") == 0) {
printf("[User2] Hello!\n");
}
}
return 0;
}
As others have pointed out, you're trying to store a string into a char variable using scanf when chars are only meant to store one character. You should you use a char * or char[] variable to hold your string instead. So change
char x;
printf("[User1] ");
scanf("%s",&x);
//...rest of your code...
to
char * x = malloc(sizeof(char) * 10); //can hold up to ten characters
printf("[User1] ");
scanf("%s",x);
//...rest of your code...
free(x);
Note that if you just want to use a char array instead of a pointer you can replace the first line above with something like char x[10]; and get rid of free(x);
char input[1000];
I want to copy input into a dynamically allocated character array, how do I approach this problem.
So far I have used strncpy, but get lots of errors.
Are you looking for something like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
int i;
char input[1000] = "Sample string";
char *in = malloc(1000 * sizeof(char)); // use dynamic number instead of 1000
strcpy(in, input);
for (i = 0; i < 5; ++i) { // intentionally printing the first 5 character
printf("%c", in[i]);
}
}
The output is:
Sampl
Edit: In C++ the cast is required for malloc, so I write:
(char *)malloc(1000 * sizeof(char))
But in C, never cast the result of malloc().
What you can do is just use strcpy() offer by C string.h after dynamically allocating memory to your array, as shown:
char *input = malloc(1000*sizeof(char));
and if the string you are trying to copy to variable input exceeds the allocated memory size (strlen > 999: don't forget! String has a null terminator '\0' that takes up the additional 1 char space), just realloc as shown:
input = realloc(input, 1000*2*sizeof(char));
/* check if realloc works */
if (!input) {
printf("Unexpected null pointer when realloc.\n");
exit(EXIT_FAILURE);
}