How to fetch a specific substring from string? - c

In this code, I want to select the second word from the file and the third one also and print that one but I am unable to fetch specific words. I searched a lot and done a lot of stuff to fetch the second and third words from the str variable but unable to do that?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char str[] = "bilal,1000,savings";
char toFind, name[20], account[20];
char * word1;
char * word2;
char * word3;
int i=0, numberOfFields = 3, amount;
static const char * listing[] = {"Name","Amount","Account"};
for(i=0; i<numberOfFields; i++){
printf("%d. Here is your %s \n", i, listing[i]);
}
printf("Which one: ");
scanf("%c", &toFind);
if(toFind == '0'){
printf("selected zero\n");
word1 = strtok(str, ",");
printf("%s\n", word1);
}
else if(toFind == '1'){
printf("selected one\n");
}
else if(toFind == '2'){
printf("selected two\n");
}
return 0;
}

If you parse each line up front, it makes it simpler:
char str[] = "bilal,1000,savings";
char *word1 = strtok(str, ",");
char *word2 = strtok(NULL, ",");
char *word3 = strtok(NULL, ",");
printf("Which one: ");
scanf("%c", &toFind);
if(toFind == '0'){
printf("selected zero\n");
printf("%s\n", word1);
}
else if(toFind == '1'){
printf("selected one\n");
printf("%s\n", word2);
}
else if(toFind == '2'){
printf("selected two\n");
printf("%s\n", word3);
}

Related

How to print part of a tokenized string from a file in C

I am having some trouble with a tokenized string that is a line from a file. I want to print the line from where the token is found, but I cannot seem to find a way around it. Please, ignore the output to the file part as well as the author, class and method if statements as I have them sorted out.
For example, I want it to print from this line: #return the matric only this part: the matric
Code:
#include <stdio.h>
#include <string.h>
int main (int argc, char **argv)
{
char line [1000];
char *delimeters = ".,; \t\n";
int total_lines = 0;
int total_comments = 0;
int nonblank_lines = 0;
FILE *input = fopen (argv[2], "r");
FILE *output = fopen (argv[4],"w");
while(fgets(line,1000,input) != NULL)
{
char *word = strtok(line, delimeters);
total_lines++;
if(word != NULL)
{
nonblank_lines++;
}
if(word != NULL && strcmp(word,"/**") == 0)
{
total_comments++;
}
while(word != NULL)
{
if(word != NULL && strcmp(word,"#author") == 0)
{
char *author_name = strtok(NULL, delimeters);
char *author_surname = strtok(NULL, delimeters);
printf ("Author: %s %s\n", author_name, author_surname);
}
if(word != NULL && strcmp(word,"public") == 0)
{
char *jmp = strtok(NULL, delimeters);
if(jmp != NULL && strcmp(jmp,"class") == 0)
{
char *class_name = strtok(NULL, delimeters);
printf ("Class %s\n", class_name);
}else{
char *method_name = strtok(NULL, delimeters);
printf ("Method %s\n", method_name);
}
}
if(word != NULL && strcmp(word,"#return") == 0)
{
printf("Enters IF 4\n");
char *return_value = strtok(NULL, delimeters);
printf ("Returns: %s\n", return_value;
}
/*if(word != NULL && strcmp(word,"#param") == 0)
{
printf("Enters IF 5\n");
char *parameters = strtok(NULL, delimeters);
printf("Parameter: %s\n", parameters);
//int param_found
}*/
word = strtok(NULL, delimeters);
}
}
printf ("The total number of lines is %d\n", total_lines);
printf ("The total number of non-blank lines is %d\n", nonblank_lines);
printf ("The total number of comments is %d\n", total_comments);
fclose(input);
fclose(output);
return 0;
}
So following my comment, you'd want something like this block for each if statement:
while(fgets(line, 1000, input) != NULL)
{
char *first_word_in_line = strtok(line, delimeters);
if(strcmp(first_word_in_line, "#return") == 0)
{
char *word = strtok(NULL, delimeters);
printf ("Returns: ");
while(word != NULL)
{
printf ("%s ", word);
word = strtok(NULL, delimeters);
}
printf("\n");
}
}
Note that I added another variable first_word_in_line on top word - it's not a must but it makes it less confusing when you code and it shows that the first word in the line has a different meaning because that's just the title.
Also, you should read about strcmp vs. strncmp. Usually it's a good practise to use strncmp.
The answer I got is this:
if(word != NULL && strcmp(word,"#return") == 0)
{
char *return_value = strtok(NULL, delimeters);
printf ("Returns: ");
while(return_value != NULL)
{
printf ("%s ", return_value);
return_value = strtok(NULL, delimeters);
}
printf("\n");
}
You messed a bit with the parameters at the beginning.
./program.c input.txt output.txt
argv[0] will give you the name of the program (in this case program.c), argv[1] the first param you pass (input.txt) and argv[2] the second parameter (output.txt)
There was also a missing bracket and for a comment /* comment */ one star in c is enough.
That fixed it worked for me.
But be aware if you cut the comment with strtok() the way you do it, there has to be a delimiter left and right to the start of your comment.
somecode; /* This should be recognized */
somecode;/* This not */
somecode; /*This neither */
Here ist the corrected code:
#include <stdio.h>
#include <string.h>
int main (int argc, char **argv)
{
char line [1000];
char *delimeters = ".,; \t\n";
int total_lines = 0;
int total_comments = 0;
int nonblank_lines = 0;
FILE *input = fopen (argv[1], "r");
FILE *output = fopen (argv[2],"w");
while(fgets(line,1000,input) != NULL)
{
char *word = strtok(line, delimeters);
total_lines++;
if(word != NULL)
{
nonblank_lines++;
}
if(word != NULL && strcmp(word,"/*") == 0)
{
total_comments++;
}
while(word != NULL)
{
if(word != NULL && strcmp(word,"#author") == 0)
{
char *author_name = strtok(NULL, delimeters);
char *author_surname = strtok(NULL, delimeters);
printf ("Author: %s %s\n", author_name, author_surname);
}
if(word != NULL && strcmp(word,"public") == 0)
{
char *jmp = strtok(NULL, delimeters);
if(jmp != NULL && strcmp(jmp,"class") == 0)
{
char *class_name = strtok(NULL, delimeters);
printf ("Class %s\n", class_name);
}else{
char *method_name = strtok(NULL, delimeters);
printf ("Method %s\n", method_name);
}
}
if(word != NULL && strcmp(word,"#return") == 0)
{
printf("Enters IF 4\n");
char *return_value = strtok(NULL, delimeters);
printf ("Returns: %s\n", return_value);
}
/*if(word != NULL && strcmp(word,"#param") == 0)
{
printf("Enters IF 5\n");
char *parameters = strtok(NULL, delimeters);
printf("Parameter: %s\n", parameters);
//int param_found
}*/
word = strtok(NULL, delimeters);
}
}
printf ("The total number of lines is %d\n", total_lines);
printf ("The total number of non-blank lines is %d\n", nonblank_lines);
printf ("The total number of comments is %d\n", total_comments);
fclose(input);
fclose(output);
return 0;
}

Programming error - name truncated and cannot convert parameter 1 from 'int' to 'char *'

Hi I need some help for my assignment. I'm kind of newbie to programming. I hit into some errors for the program.
the name is truncated to numbers
hit into error cannot convert parameter 1 from 'int' to 'char *'
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //for strtok
#include <ctype.h>
//function prototypes
struct Student* readFile(int*, struct Student*);
char *trimwhitespace(char *str);
void listRecords(struct Student*, int);
void writeFile(struct Student*, int);
int isValid1(char *);
int isValidatt(char *);
int isValidatt2(char [10][10]);
int isValid3(char *);
struct Student {
char SID [10];
char name[30];
char code [20];
char attendance [10][10] ;
int test1;
int test2;
int tutorial;
int exam;
};
int main() {
int numStudents = 0;
int choice;
struct Student *students; //array of students
students = (struct Student *) malloc(sizeof(struct Student));
//create one empty slot
do {
printf("[1] Read from file \n");
printf("[2] List records \n");
printf("[3] Write to file \n");
printf("[4] Exit \n");
printf("Choice: ");
scanf("%i", &choice);
switch(choice) {
case 1:
printf("Reading from file .. \n");
students = readFile(&numStudents, students);
printf("Read from file %i customers\n", numStudents);
break;
case 2:
printf("Listing records .. \n");
listRecords(students, numStudents);
break;
case 3:
printf("Writing to file .. \n");
writeFile(students, numStudents);
break;
case 4:
printf("Bye .. \n");
break;
}
} while(choice != 4);
return 0;
}
struct Student* readFile(int *numStudents, struct Student *students) {
FILE *inFile; //file handle
char filename[50];
char line[255]; //for each line
int i = 0, j;
char *token;
printf("Enter filename: "); //prompt user for filename
scanf("%s", filename);
//check that file can be found and opened
if ((inFile = fopen(filename, "r")) == NULL) {
printf("Open failed : %s\n", filename) ;
exit(1) ;
}
//create one empty slot
students = (struct Student *) malloc(sizeof(struct Student));
//reading file, line by line
while (fgets(line,255, inFile)!=NULL) {
token = strtok(line, ","); //comma is the delimiter/separator
strcpy(students[i].SID, trimwhitespace(token));
printf("%s\n", students[i].SID);
token = strtok(NULL, ","); //get next token -> name
strcpy(students[i].name, trimwhitespace(token));
printf("%s\n", students[i].name);
token = strtok(NULL, ","); //get next token -> class code
strcpy(students[i].code, trimwhitespace(token));
printf("%s\n", students[i].code);
for(j = 0; j < 10; j++) {
token = strtok(NULL, ","); //get next token -> attendance
strcpy(students[i].attendance[j], trimwhitespace(token));
printf("%s\n", students[i].attendance[j]);
}
token = strtok(NULL, ","); //get next token -> test 1
strcpy(students[i].name, trimwhitespace(token));
//students[i].test1 = atoi(trimwhitespace(token));
printf("%d\n", students[i].test1);
token = strtok(NULL, ","); //get next token -> test 1
strcpy(students[i].name, trimwhitespace(token));
//students[i].test2 = atoi(trimwhitespace(token));
printf("%d\n", students[i].test2);
token = strtok(NULL, ","); //get next token -> tutorial
strcpy(students[i].name, trimwhitespace(token));
//students[i].tutorial = atoi(trimwhitespace(token));
printf("%d\n", students[i].tutorial);
token = strtok(NULL, ","); //get next token -> exam
strcpy(students[i].name, trimwhitespace(token));
//students[i].exam = atoi(trimwhitespace(token));
printf("%d\n", students[i].exam);
i++;
//resize it to add in one extra slot
students = (struct Student *) realloc(students, (i+1)*sizeof(struct Student));
}
fclose(inFile); //close the file
*numStudents = i;
return students;
}
void listRecords(struct Student *students, int n) {
int i;
if(n == 0) {
printf("No Student in list .. \n");
} else {
for(i = 0; i < n; i++) {
printf("[Student #%d]\n", i+1);
printf("%s %s %s %s %s %s %s %s %s %s %s %s %d %d %d %d \n",
students[i].SID, students[i].name, students[i].code, students[i].attendance [0], students[i].attendance [1], students[i].attendance [2], students[i].attendance [3], students[i].attendance [4],
students[i].attendance [5], students[i].attendance [6], students[i].attendance [7], students[i].attendance [8], students[i].test1, students[i].test2, students[i].tutorial, students[i].exam, "\n");
}
}
}
void writeFile(struct Student *students, int n) {
FILE *inFile1;
FILE *inFile2;
char filename1[30] = "EN0273-Errors(LeeAiWen).txt";
char filename2[30] = "EN0273-Valid(LeeAiWen).csv";
int i, valid;
Student s;
if ((inFile1 = fopen(filename1, "w")) == NULL)
{
printf("Open failed : %s\n", filename1) ;
exit(1) ;
}
if ((inFile2 = fopen(filename2, "w")) == NULL)
{
printf("Open failed : %s\n", filename1) ;
exit(1) ;
}
valid = 1;
for(i = 0; i < n; i++) {
s = students[i];
if(isValid1(s.SID) == 0) {
fprintf(inFile1, "%s %s %s \n", s.SID, s.name, s.code);
}else {fprintf(inFile2, "%s %s %s \n", s.SID, s.name, s.code);}
if(isValidatt2(s.attendance) == 0) {
fprintf(inFile1, "%s %s %s \n", s.SID, s.name, s.code);
}else {fprintf(inFile2, "%s %s %s \n", s.SID, s.name, s.code);}
if(isValid3(s.test2) == 0) {
fprintf(inFile1, "%s %s %s \n", s.SID, s.name, s.code);
}else {fprintf(inFile2, "%s %s %s \n", s.SID, s.name, s.code);}
/*
if(valid == 0) {
fprintf(inFile1, "%s %s %s \n", s.SID, s.name, s.code);
} else {
fprintf(inFile2, "%s %s %s \n", s.SID, s.name, s.code);
}
*/
}
fclose(inFile1);
fclose(inFile2);
}
int isValid3( char *id) { //returns 1 if valid, otherwise 0
int i;
if(atoi (id) > 60) { return 0; } // used 'atoi' to convert 'id' to int to compare with '60' which is an int value, marks should not be more than 60 max
for(i = 0; i < 2; i++) { // only 2 digits are allowed and no characters
if(isdigit(id[i]) == 0) { return 0; }
}
return 1;
}
char *trimwhitespace(char *str)
{
char *end;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
// Write new null terminator
*(end+1) = 0;
return str;
}
Your Code have 3 Issues :-
In function "writeFile()" you passed unknown type structure name. You skipped to write struct before Student s;
No Definition was found for inValid1() and Invalid2() function.
You passed integer argument in a inValid2() function which expected char data.
I have modified you code just have a look :-
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //for strtok
#include <ctype.h>
//function prototypes
struct Student* readFile(int*, struct Student*);
char *trimwhitespace(char *str);
void listRecords(struct Student*, int);
void writeFile(struct Student*, int);
int isValid1(char *);
int isValidatt(char *);
int isValidatt2(char [10][10]);
int isValid3(int *);
struct Student {
char SID [10];
char name[30];
char code [20];
char attendance [10][10] ;
int test1;
int test2;
int tutorial;
int exam;
};
int main() {
int numStudents = 0;
int choice;
struct Student *students; //array of students
students = (struct Student *) malloc(sizeof(struct Student));
//create one empty slot
do {
printf("[1] Read from file \n");
printf("[2] List records \n");
printf("[3] Write to file \n");
printf("[4] Exit \n");
printf("Choice: ");
scanf("%i", &choice);
switch(choice) {
case 1:
printf("Reading from file .. \n");
students = readFile(&numStudents, students);
printf("Read from file %i customers\n", numStudents);
break;
case 2:
printf("Listing records .. \n");
listRecords(students, numStudents);
break;
case 3:
printf("Writing to file .. \n");
writeFile(students, numStudents);
break;
case 4:
printf("Bye .. \n");
break;
}
} while(choice != 4);
return 0;
}
struct Student* readFile(int *numStudents, struct Student *students) {
FILE *inFile; //file handle
char filename[50];
char line[255]; //for each line
int i = 0, j;
char *token;
printf("Enter filename: "); //prompt user for filename
scanf("%s", filename);
//check that file can be found and opened
if ((inFile = fopen(filename, "r")) == NULL) {
printf("Open failed : %s\n", filename) ;
exit(1) ;
}
//create one empty slot
students = (struct Student *) malloc(sizeof(struct Student));
//reading file, line by line
while (fgets(line,255, inFile)!=NULL) {
token = strtok(line, ","); //comma is the delimiter/separator
strcpy(students[i].SID, trimwhitespace(token));
printf("%s\n", students[i].SID);
token = strtok(NULL, ","); //get next token -> name
strcpy(students[i].name, trimwhitespace(token));
printf("%s\n", students[i].name);
token = strtok(NULL, ","); //get next token -> class code
strcpy(students[i].code, trimwhitespace(token));
printf("%s\n", students[i].code);
for(j = 0; j < 10; j++) {
token = strtok(NULL, ","); //get next token -> attendance
strcpy(students[i].attendance[j], trimwhitespace(token));
printf("%s\n", students[i].attendance[j]);
}
token = strtok(NULL, ","); //get next token -> test 1
strcpy(students[i].name, trimwhitespace(token));
//students[i].test1 = atoi(trimwhitespace(token));
printf("%d\n", students[i].test1);
token = strtok(NULL, ","); //get next token -> test 1
strcpy(students[i].name, trimwhitespace(token));
//students[i].test2 = atoi(trimwhitespace(token));
printf("%d\n", students[i].test2);
token = strtok(NULL, ","); //get next token -> tutorial
strcpy(students[i].name, trimwhitespace(token));
//students[i].tutorial = atoi(trimwhitespace(token));
printf("%d\n", students[i].tutorial);
token = strtok(NULL, ","); //get next token -> exam
strcpy(students[i].name, trimwhitespace(token));
//students[i].exam = atoi(trimwhitespace(token));
printf("%d\n", students[i].exam);
i++;
//resize it to add in one extra slot
students = (struct Student *) realloc(students, (i+1)*sizeof(struct Student));
}
fclose(inFile); //close the file
*numStudents = i;
return students;
}
void listRecords(struct Student *students, int n) {
int i;
if(n == 0) {
printf("No Student in list .. \n");
} else {
for(i = 0; i < n; i++) {
printf("[Student #%d]\n", i+1);
printf("%s %s %s %s %s %s %s %s %s %s %s %s %d %d %d %d \n",
students[i].SID, students[i].name, students[i].code, students[i].attendance[0], students[i].attendance[1], students[i].attendance[2], students[i].attendance[3], students[i].attendance[4],
students[i].attendance[5], students[i].attendance[6], students[i].attendance[7], students[i].attendance[8], students[i].test1, students[i].test2, students[i].tutorial, students[i].exam, "\n");
}
}
}
void writeFile(struct Student *students, int n) {
FILE *inFile1;
FILE *inFile2;
char filename1[30] = "EN0273-Errors(LeeAiWen).txt";
char filename2[30] = "EN0273-Valid(LeeAiWen).csv";
int i, valid;
struct Student s;
if ((inFile1 = fopen(filename1, "w")) == NULL)
{
printf("Open failed : %s\n", filename1) ;
exit(1) ;
}
if ((inFile2 = fopen(filename2, "w")) == NULL)
{
printf("Open failed : %s\n", filename1) ;
exit(1) ;
}
valid = 1;
for(i = 0; i < n; i++) {
s = students[i];
/* if(isValid1(s.SID) == 0) {
fprintf(inFile1, "%s %s %s \n", s.SID, s.name, s.code);
}else {fprintf(inFile2, "%s %s %s \n", s.SID, s.name, s.code);}
if(isValidatt2(s.attendance) == 0) {
fprintf(inFile1, "%s %s %s \n", s.SID, s.name, s.code);
}else {fprintf(inFile2, "%s %s %s \n", s.SID, s.name, s.code);}
*/
if(isValid3(&s.test2) == 0) {
fprintf(inFile1, "%s %s %s \n", s.SID, s.name, s.code);
}else {fprintf(inFile2, "%s %s %s \n", s.SID, s.name, s.code);}
/*
}
fclose(inFile1);
fclose(inFile2);
}
int isValid3(int *id) { //returns 1 if valid, otherwise 0
int i;
if(*id > 60) { return 0; } // used 'atoi' to convert 'id' to int to compare with '60' which is an int value, marks should not be more than 60 max
for(i = 0; i < 2; i++) { // only 2 digits are allowed and no characters
if(id[i] == 0) { return 0; }
}
return 1;
}
char *trimwhitespace(char *str)
{
char *end;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
// Write new null terminator
*(end+1) = 0;
return str;
}

Can't take input in a dynamically allocated string in c

I've been writing a HTML generator in C. After some research I found some code that allows me to take input in a array that allocates more memory to it if you need it. The problem is that after a couple of times, the code stops working.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *inputString(FILE *fp, size_t size);
int main(){
char *nameOfFile;
char *multiF;
int choice;
FILE *f;
printf("Name of file: ");
nameOfFile=inputString(stdin, 10);
f = fopen(strcat(nameOfFile,".html"),"w+");
fprintf(f, "<head>\n");
printf("Title: ");
multiF=inputString(stdin, 10);
fprintf(f, "\t<title>%s</title>\n</head>\n<body>\n", multiF);
while(choice != 99){ //Code stops working in while loop
printf("What do you want to do?\n");
printf("[1]Headings\n");
printf("[2]Paragraphs\n");
printf("[99]Exit\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("What size[1-6]? ");
scanf("%d",&choice);
if(choice < 7 && choice > 0){
printf("Heading[%d]:",choice);
multiF=inputString(stdin,10);
fprintf(f,"<h%d>%s</h%d>",choice,multiF,choice);
}else{
printf("Input something useful...\n");
}
break;
case 2:
printf("Paragraph: ");
multiF=inputString(stdin,10);
fprintf(f,"<p>%s</p>",multiF);
break;
case 99:
break;
default:
printf("Input something useful...\n");
}
}
fprintf(f,"</body>");
free(multiF);
free(nameOfFile);
return 0;
}
char *inputString(FILE *fp, size_t size){
char *str;
int ch;
size_t len=0;
str = realloc(NULL, sizeof(char)*size);
if(!str)return str;
while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
str[len++]=ch;
if(len==size){
str = realloc(str, sizeof(char)*(size+=16));
if(!str)return str;
}
}
str[len++]='\0';
return realloc(str, sizeof(char)*len);
}
This should work:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void inputString(char **str, FILE *fp); // No char *str, because we need to change the value of pointer str
int main(){
char *nameOfFile = malloc(0);
char *multiF = malloc(0); // Calling malloc() for later free()
int choice = 0; // Initialization
FILE *f;
printf("Name of file: ");
inputString(&nameOfFile, stdin);
nameOfFile = realloc(nameOfFile, strlen(nameOfFile) + 5); // You need more memory for ".html"
strcat(nameOfFile, ".html");
f = fopen(nameOfFile, "w");
fprintf(f, "<head>\n");
printf("Title: ");
inputString(&multiF, stdin);
fprintf(f, "\t<title>%s</title>\n</head>\n<body>\n", multiF);
while(choice != 99){
printf("What do you want to do?\n");
printf("[1]Headings\n");
printf("[2]Paragraphs\n");
printf("[99]Exit\n");
scanf(" %d%*c", &choice); // " %d" to discard whitespace characters, and "%*c" to consume '\n'
switch(choice){
case 1:
printf("What size[1-6]? ");
scanf(" %d%*c", &choice);
if(choice < 7 && choice > 0){
printf("Heading[%d]:", choice);
inputString(&multiF, stdin);
fprintf(f, "<h%d>%s</h%d>", choice, multiF, choice);
}else{
printf("Input something useful...\n");
}
break;
case 2:
printf("Paragraph: ");
inputString(&multiF, stdin);
fprintf(f, "<p>%s</p>", multiF);
break;
case 99:
break;
default:
printf("Input something useful...\n");
break;
}
}
fprintf(f, "</body>");
free(multiF);
free(nameOfFile);
fclose(f); // Don't forget to close the file
return 0;
}
void inputString(char **str, FILE *fp){
int ch;
size_t size = 1, index = 0;
free(*str);
*str = malloc(size);
if(!*str)
return;
while(EOF != (ch = fgetc(fp)) && ch != '\n'){
(*str)[index++] = ch;
if(index == size){
*str = realloc(*str, size += 16); // sizeof (char) is guaranteed to be 1 by the standard
if(!*str)
return;
}
}
(*str)[index] = '\0'; // No need to increase index
}
See my comments for the details.
There are some issues in your code:
After scanf("%d",&choice);, a '\n' will be left in stdin. When it is met by inputStrng(), the function stops generating string immediately.
To change the value of a pointer variable in a function, you need to pass a pointer to pointer, such as char **str.
You forgot to close the file, which may cause information loss.

while loop terminating before it is supposed to C

This program is supposed to copy an existing txt file to a new txt code file. However is isn't working right. For some reason it always stops after the third iteration.
Suggestions?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char fileNameIn[100];
char fileNameOut[100];
FILE *ptrIn = NULL; //____ File Pointers
FILE *ptrOut = NULL;
char str[1000]; //this is used at fgets and it obtains sentences
/*_________________Counter variables)*/
char *token;
int ctr = 0;
int ndel = -1;
char wordA[10];
char sentence[101];
char del[10] = " !-,.";
;
int temp = 0;
printf("Enter the input filename: \n");
// gets(fileNameIn);
scanf("%s", fileNameIn);
//printf("You entered: %s\n",fileNameIn);
printf("Enter the output filename: \n");
scanf("%s", fileNameOut);
ptrIn = fopen(fileNameIn, "r"); // r is to read
ptrOut = fopen(fileNameOut, "w"); //w is to write on file
if (ptrIn == NULL || ptrOut == NULL) {
printf("Unable to open file\n");
exit(1);
}
//while(fgets (str,sizeof(str), ptrIn) )
while (fgets(str, sizeof(str), ptrIn)) { // while we are not at the end of the file
puts(str);
// if(temp==0)
// {
token = strtok(str, del);
temp = -1;
printf(
"Enter position of word to delete (Start counting at 0). Enter -1 to skip deletion:\n");
scanf("%d", &ndel);
printf("You selected: %d\n", ndel);
while (token != NULL) // while loop inside a sentence
{
if (ctr != ndel) {
strcpy(wordA, token);
}
token = strtok(NULL, del);
if (ctr != ndel) {
strcat(sentence, wordA);
strcat(sentence, " ");
printf("halfway?");
}
ctr++;
} // endof sentence loop
fprintf(ptrOut, "%s", sentence);
printf("the sentence is now:\n%s", sentence);
printf("___________________________________________");
printf("\n");
strcpy(sentence, "");
ctr = 0;
ndel = -1;
} //end of while loop eof
printf("Finish the main: ");
fflush(ptrOut);
fclose(ptrIn);
fclose(ptrOut);
return EXIT_SUCCESS;
}
This is an example of the existing file:
test.txt:
hello my name is john.
this is a test.
after the third line the while
loop stops
this does the get copied
You strcat() to senetence wihtout initializing it, strcat() will search for the terminating nul byte of it's first argument and start copying characters from it's second argument start from that position, so a simple
sentence[0] = '\0';
right after the outer while loop will fix it, but your code needs reformatting and you should make it safer by checking every single potential undefined behavior cause.
This is the code and it now works correctly
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char fileNameIn[100] = {0};
char fileNameOut[100] = {0};
FILE *ptrIn = NULL;
FILE *ptrOut = NULL;
char str[1024] = {0};
char *token = NULL;
int ctr = 0;
int ndel = -1;
char wordA[1024] = {0};
char sentence[1024] = {0};
char del[] = " !-,.";
int temp = 0;
printf("Enter the input filename > ");
fflush(stdout);
scanf("%99s", fileNameIn);
printf("Enter the output filename > ");
fflush(stdout);
scanf("%99s", fileNameOut);
ptrIn = fopen(fileNameIn, "r"); // r is to read
if (ptrIn == NULL)
{
printf("Unable to open file %s\n", fileNameIn);
return -1;
}
ptrOut = fopen(fileNameOut, "w"); // w is to write on file
if (ptrOut == NULL)
{
fclose(ptrIn);
printf("Unable to open file %s\n", fileNameOut);
return -1;
}
while (fgets(str, sizeof(str), ptrIn)) // while we are not at the end of the file
{
puts(str);
token = strtok(str, del);
temp = -1;
printf("Enter position of word to delete (Start counting at 0) `-1 to skip deletion' > ");
if (scanf("%d", &ndel) != 1)
continue;
printf("You selected: %d\n", ndel);
sentence[0] = '\0';
while (token != NULL)
{
if (ctr != ndel)
strcpy(wordA, token);
token = strtok(NULL, del);
if (ctr != ndel)
{
strcat(sentence, wordA);
strcat(sentence, " ");
}
ctr++;
}
fprintf(ptrOut, "%s", sentence);
printf("the sentence is now:\n%s", sentence);
printf("\n");
ctr = 0;
ndel = -1;
}
printf("Finish the main: ");
fflush(ptrOut);
fclose(ptrIn);
fclose(ptrOut);
return EXIT_SUCCESS;
}

Searching type char** for a string

Note that this is a repost, I have clarified my post to be more understandable
void searchArray(char ***array, int count){
char * word = "";
printf("Enter a word: ");
fscanf(stdin, " ");
fscanf(stdin, "%c", &word);
bool found = false;
for(int i = 0; i < count; i++){
if(strcmp(word, (*array)[i]) == 0){
found = true;
break;
}
}
if(found) printf("%s found!\n", word);
else if (!found) printf("%s not found!\n", word);
}
In testing, the code returns " not found!" for every input.
The above is the code that I have for searching and traversing an array of type char ** ... I'm not sure whether I have my traversing logic wrong or if I'm improperly using strcmp... Any help would be greatly appreciated!
Here is the code for insertion which may help to clarify what exactly I'm trying to do:
int insertWord(char **array, int *count, char word[])
{
char *wordPtr;
wordPtr = (char *)malloc((strlen(word) + 1) * sizeof(char));
if (wordPtr == NULL)
{
fprintf(stderr," Malloc of array[%d] failed!\n", *count);
return -1;
}
/* Memory for this word has been allocated, so copy characters
and insert into array */
strcpy(wordPtr, word);
array[*count] = wordPtr;
(*count)++;
return 0;
}
My task is to search for a specific string in this data.
void searchArray(char ***array, int count){
char word[80];
printf("Enter a word: ");
fscanf(stdin, " ");
fscanf(stdin, "%s", word);
bool found = false;
for(int i = 0; i < count; i++){
if(strcmp(word, (*array)[i]) == 0){
found = true;
break;
}
}
if(found) printf("%s found!\n", word);
else if (!found) printf("%s not found!\n", word);
}
This code works perfectly. I think that since I was using fscanf(stdin, "%c", &word); it was reading in the open space character from the previous line (in the buffer) and then searching for it...is that how that works?
Thanks!

Resources