Can someone please tell me what is wrong with strcmp? I don't understand why I am getting a segmentation fault when comparing array of strings and string.
I figured out my problem just not sure how to go about fixing it. I will eventually be putting nam into strings based on my hash function. Before I do this though I want to check if my string already exists in my string array. If it does not exist I want to put it into the array. If it does exist I don't want to put it into my array. So I am guessing when I use strcmp on a non existent value I get null. Is there a good way to handle this?
char *strings[100];
char nam[100];
int g = 0;
while (fscanf(pFile, "%s %d", nam, &val) !=EOF)
{
strings[k] = nam;
printf(" string is %s .\n", strings[k]);
k++;
i = 0;
g = (int) strcmp (strings[0], nam);
printf("g is %d \n", g);
for(i = 0; i < 5; i++)
{
if(strcmp (strings[i], nam) == 0)
{
printf(" strings[i] is equal");
}
}
printf(" Bust out");
}
It also didn't like this. I figured I was getting a null on the non existent values so this would work.
for(i = 0; i < 5; i++)
{
if(strcmp (strings[i], nam) == '\0')
{
printf(" strings[i] is equal");
}
}
I dont understand how You are getting an error. This is How i tested it
#include <stdio.h>
#include <string.h>
int main()
{
char *strings[100];
char nam[100];
strcpy(nam, "ansh");
strings[1] = nam;
printf("\n%s", nam);
printf("\n%s", strings[1]);
int k = strcmp(nam, strings[1]);
printf("\n%d\n", k);
return 0;
}
OUTPUT-
ansh
ansh
0
you should malloc for nam or strings[k] to keep value,in the while loop ,when nam changes ,strings[k] will point somewhere unknown.
char *strings[100];
char nam[100];
int g = 0;
while (fscanf(pFile, "%s %d", nam, &val) !=EOF)
{
char *tmp = malloc( strlen(nam) + 1 );
strcpy( tmp , nam );
strings[k] = tmp;
printf(" string is %s .\n", strings[k]);
k++;
g = strcmp (strings[i], nam);
printf("g is %d \n", g);
}
Related
trying to read in from a text file with 10 lines of 10 numbers separated by spaces. I want to directly save each number into a space in the matrix numList.
Really not sure what the problem is with my code, I think it might be because i'm not initializing the matrix correctly or something. Any help appreciated
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE* fpointer = fopen("numbers.txt", "r");
if (fpointer == NULL) {
printf("No file found");
return 1;
}
// INITIALISE MATRIX
char* numList[10][10];
char buffer[300];
// COPY NUMBERS INTO MATRIX
int i = 0;
while (fgets(buffer, 300, fpointer)) {
int j = 0;
char* p = strtok(buffer, " ");
while ((p != NULL)&&(j<10)) {
printf(" %s ",p);
strcpy(numList[i][j],p);
p = strtok(NULL, " ");
j++;
}
printf("\n");
i++;
}
printf("\n\n");
//Print Final Matrix
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
printf("%s ", numList[i][j]);
}
printf("\n");
}
fclose(fpointer);
return 0;
}
Problem is occurring on the strcpy(numList[i][j],p) function but i'm not sure why.
Output: Exception thrown at 0x7C15EE87 (ucrtbased.dll) in asd.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.
No memory is allocated for numList[i][j]
You can use strdup instead of strcpy
while (fgets(buffer, 300, fpointer)) {
int j = 0;
char* p = strtok(buffer, " ");
while ((p != NULL)&&(j<10)) {
printf(" %s ",p);
numList[i][j] = strdup(p);
p = strtok(NULL, " ");
j++;
}
printf("\n");
i++;
}
I am very confused to create a function which will print a string and ask user to enter two numbers and then function will replace those number of words with one another.
I have added the image below as sample.
enter image description here
This is my homework, I have created other 3 functions, but don't really get this one.
Could somebody please help me how can I convert the words into numbers and then replace those number of words with one another.
This is my program it can break the string into words but how can i replace position of words.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
printf(" Input a string : ");
fgets(str1, sizeof str1, stdin);
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[i];
j++;
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
Seems to me that you are doing pretty good so far (your code can't handle comma but you can add that later). So let's assume that your newString actually contains the individual words.
So your next step is to construct a new string str2 from the individual words you have in newString. While you do that you can simply swap the two words of interest. To build the new string the strcat function could be helpful.
The code below is not fully correct but it may give you some ideas for getting on with your homework:
int lowest_index_to_swap = some_number
int highest_index_to_swap = some_higher_number
char str2[100] = "";
for (i=0; i<number_of_words_found; ++i)
{
if (i == lowest_index_to_swap)
strcat(str2, newString[highest_index_to_swap];
else if (i == highest_index_to_swap)
strcat(str2, newString[lowest_index_to_swap];
else
strcat(str2, newString[i];
strcat(str2, " ";
}
Here is code snippet what I tried in my local server based on your input in image.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 100
#define WORDLEN 20
int main() {
int place_1, place_2, count = 0, i, k =0;
char str[] = "Hi, welcome to C programming";
char **words = (char **)malloc(sizeof(char *)*SIZE);
if(!words){
printf("malloc of words failed!\n");
exit(1);
}
char *temp = (char *)malloc(sizeof(char)*WORDLEN);
if(!temp){
printf("malloc of temp failed!\n");
exit(1);
}
for(i = 0; str[i] != '\0'; count++){
words[count] = (char *)malloc(sizeof(char)*WORDLEN);
if(!words[count]){
printf("malloc of words[%d] failed!\n", count);
exit(1);
}
sscanf(str+i, "%s", words[count]);
i += 1+strlen(words[count]);
printf("%d %s %d\n", count, words[count], i);
}
printf("Enter the word places to replace: ");
if(scanf("%d %d", &place_1, &place_2) < 2){
printf("scanf failed!\n");
exit(1);
}
temp = words[place_1 - 1];
words[place_1 - 1] = words[place_2 - 1];
words[place_2 - 1] = temp;
for(i = 0; i < count; i++){
sprintf(str+k, "%s ", words[i]);
k += 1+strlen(words[i]);
}
printf("str: %s\n", str);
free(temp);
for(i = 0; i < count; i++){
free(words[i]);
}
free(words);
}
Hope it helps.
hey so i m trying to read numbers from text file and put them into an array but ive been getting weird numbers when i try to print them. text file looks like:
45
77
8
...
i guess theres something wrong with the loop i m using but i cant seem to find out what.
thanks for your help!
code:
#define MAX_ARRAY_SIZE 20
int main(int argc, char * argv[])
{
FILE *myFile;
int myArray[MAX_ARRAY_SIZE];
//char filename[32];
//printf("enter filename\n");
//scanf("%s", filename);
myFile = fopen("asdf.txt", "r");
if (!myFile) {
printf("cant open file\n");
return 1;
}
int status;
int i = 0;
while ((status = fscanf(myFile, "%2d", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
fclose(myFile);
int a;
for (a = 0; i < MAX_ARRAY_SIZE; ++i) {
printf("%d ", myArray[i]);
}
printf("\n");
return 0;
}
The problem is in your print loop:
for (a = 0; i < MAX_ARRAY_SIZE; ++i)
There is no guarantee you are reading MAX_ARRAY_SIZE values. Also, if you ar using 'a' as your loop iterator, then you need to use 'a'. Your loop should be:
for (a = 0; a < i; ++a)
printf("%d ", myArray[a]);
You also do not need a field-width in your format-specifier, fscanf(myFile, " %d", &myArray[i])) will do.
Try this
while ((status = fscanf(myFile, "%d\n", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
True... I have not seen print loop code.. Sorry.
Problem is in print loop not fscan, please ignore my answer
I have some troubles with a small programm.
There should be inputs by the user (of different type). But when the user puts in a ZERO ("0") the loop should stop and the programm should print all inputs before zero.
If the do-while loop has finished I'd like to go through the array and print all inputs
So i tried to safe all inputs into another array. Unfortunately my problem is, that i cannot safe the input (scanf) into another array. I hope you can help me.
Here is the code:
int *iarray(unsigned int n) {
char input[MAX];
char key[] = "0";
char arr[MAX] //troublemaker
int i = 0;
int *iptr = malloc(n * sizeof(*iptr)); // or iptr = (int*) malloc(n * sizeof(int));
if (iptr != NULL) {
do {
i++;
printf("Geben sie Strings ein: ");
scanf("%s", input);
printf("%s\n", input);
/*
arr[i] = *input;
Here is the problem
*/
// i'd like to safe var input in another array for example arr[] and print it after the do- while loop
} while(strcmp(input, key) != 0); // compare if input = 0. -> if input zero then break
printf("Durchläufe %d\n", i);
}
return iptr;
}
I finally got the solution for my code, here we go. I would greatly appreciate any suggestion to improve my code. Cheers ;)
#define MAX 100
int *iarray(unsigned int n) {
char input[MAX][MAX];
char temp[MAX][MAX];
char key[] = "0";
int i = 0;
int *iptr = malloc(n * sizeof(*iptr)); // or iptr = (int*) malloc(n * sizeof(int));
if (iptr != NULL) {
do {
i++;
printf("Put in a strin: ");
scanf("%s", input[i]);
printf("%s\n", input[i]);
strcat(temp[i],input[i]); // i use a temp array to safe all input stings there
} while(strcmp(input[i], key) != 0); // compare if input = 0. -> if input zero then break
printf("Durchläufe %d\n", i);
int l;
for (int k = 1; k <= i; k++) { //first loop creates amount of input strings
printf("\n");
for (l = 0; temp[l] != NULL; l++) { // second loop prints every single letter
if (temp[k][l] == 0) { // if there is no if-statement i get a lot of crap from the output
break;
}else{
printf("%c" , temp[k][l]); // here i print my 2d arrays
}
}
printf(" -> lenght %d", l);
}
printf("\n");
}
return iptr;
}
...
you could try sprintf(arr, "%s %s", arr, input).
At the end of the while you will have the arr[] with all the input
The error occurs in the line:
printf("\n%s was found at word number(s): %d\n", search_for, pos);
I want to print my array of ints (pos) but I am not sure how to do so. I am running it through the command line and I am getting this error:
search_word.c:57:28: warning: format specifies type 'int' but the argument hastype 'int *' [-Wformat] search_for, pos);
Code:
const int MAX_STRING_LEN = 100;
void Usage(char prog_name[]);
int main(int argc, char* argv[]) {
char search_for[MAX_STRING_LEN];
char current_word[MAX_STRING_LEN];
int scanf_rv;
int loc = 0;
int pos[MAX_STRING_LEN] = {0};
int word_count = 0;
int freq = 0;
/* Check that the user-specified word is on the command line */
if (argc != 2) Usage(argv[0]);
strcpy(search_for, argv[1]);
printf("Enter the text to be searched\n");
scanf_rv = scanf("%s", current_word);
while ( scanf_rv != EOF && strcmp(current_word, search_for) != MAX_STRING_LEN ) {
if (strcmp(current_word, search_for) == 0) {
loc++;
freq++;
pos[loc] = word_count;
}
word_count++;
scanf_rv = scanf("%s", current_word);
}
if (freq == 0)
printf("\n%s was not found in the %d words of input\n",
search_for, word_count);
else
printf("\n%s was found at word number(s): %d\n",
search_for, pos);
printf("The frequency of the word was: %d\n", freq);
return 0;
} /* main */
/* If user-specified word isn't on the command line,
* print a message and quit
*/
void Usage(char prog_name[]) {
fprintf(stderr, "usage: %s <string to search for>\n",
prog_name);
exit(0);
} /* Usage */
pos is an array. You have to print it in a loop.
Do
else {
printf("\n%s was found at word number(s): ",
search_for);
for (int index = 0; index < MAX_STRING_LEN; index++)
printf("%d ", pos[index]);
printf("\n");
}
You'd need to loop over the array. C doesn't have any way to print an array of ints in a single statement:
else {
int i;
printf("\n%s was found at word number(s): ", search_for);
for ( i = 0; i < loc; ++i ) {
if (i > 0)
printf(", ");
printf("%d", pos[i]);
}
printf("\n");
}
Before that, though, make sure you increment loc at the right time. As-is, you're leaving the first element empty.
if (strcmp(current_word, search_for) == 0) {
pos[loc] = word_count;
loc++;
freq++;
}