So I have some code that gets a user input and compares it in a loop, it will check the first line, then the second, then the third and so on, however the program doesn't get another clean string variable for the next cycle of the loop, as shown here:
char text[100], blank[100];
int c = 0, d = 0;
void space(void);
int main()
{
int loop=0;
char str[512];
char string[512];
int line=1;
int dis=1;
int score=0;
char text[64];
FILE *fd;
fd = fopen("Student Usernames.txt", "r"); //Should be test
if (fd == NULL)
{
printf("Failed to open file\n");
exit(1);
}
do
{
printf("Enter the string: ");
gets(text);
while (text[c] != '\0')
{
if (!(text[c] == ' ' && text[c] == ' ')) {
string[d] = text[c];
d++;
}
c++;
}
blank[d] = '\0';
printf("Text after removing blanks\n%s\n", string);
getch();
for(loop = 0;loop<line;++loop)
{
fgets(str, sizeof(str), fd);
}
printf("\nLine %d: %s\n", dis, str);
dis=dis+1;
str[strlen(str)-1] = '\0';
if(strcmp(string,str) == 0 )
{
printf("Match\n");
score=score+2;
}
else
{
printf("Nope\n");
score=score+1;
}
getch();
}
while(!feof(fd));
printf("Score: %d",score);
getch();
}
For example: Input: Apple (1st word) , 1st line = Apple, Match, Input: Banana, 2nd line = Applea
Clearly the program has added onto to first input, I want to know how to change this
Edit: Upon reseting c and d back to 0 after each loop the output is now "AppleBanana"
Related
void issueBook(){
printf("Hii!\n");
//printf("Enter your student ID: ");
//int stdID;
//scanf("%d", &stdID);
printf("Enter the book ID\n");
int bookID;
scanf("%d", &bookID);
FILE *in_file = fopen("recordLib.txt", "r");
FILE *fp = fopen("temp.txt", "w");
struct stat sb;
stat("recordLib.txt", &sb);
char *file_contents = malloc(1024);
int mark = 0;
char ID[] = "";
while (fscanf(in_file, "%[^\n] ", file_contents) != EOF) {
int size = strlen(file_contents);
int countCom = 0;
char ID[] = "";
//printf("%d\n", size);
if(mark == 0){
for(int i=0; i<size; i++){
//printf("asdfsd\n");
//printf("%c", file_contents[i]);
if(countCom == 0 && (file_contents[i] != ',')){
strncat(ID, &file_contents[i], 1);
//printf("%c\n", file_contents[i]);
}
else if(atoi(ID) != bookID){
break;
}
else if((file_contents[i] == ',') && (countCom < 3) && (atoi(ID) == bookID)){
//printf("%c\n", file_contents[i]);
//printf("%s\n", ID);
countCom++;
}
else{
//printf("%c\n", file_contents[i]);
if(file_contents[i] == '1'){
printf("Sorry!! someone has already issued the book");
mark = 2;
break;
}
else if(file_contents[i] == '0'){
file_contents[i] = '1';
mark = 1;
break;
}
}
}
}
fwrite(file_contents, 1, size, fp);
fwrite("\n", 1, 1, fp);
}
fclose(fp);
fclose(in_file);
remove("recordLib.txt");
rename("temp.txt", "recordLib.txt");
//printf("%d\n", s);
//if(mark == 1){
// updateStu();
//}
free(file_contents);
}
I have made this function which takes the bookID from the user and then searches for it in the file:
Searching: It reads line by line and as we already know till first comma ',' it would be book ID so it will store in another string and then convert it to int. Now it will compare it with entered ID if it matches then it will update the 0 at the end to 1, else move to next line.
Error: I always getting stack smashing error when the function again returns to the main function. I am unable to find the thing that is causing the error. Also that when I run in VS code, it runs successfully but in Linux this problem occurs! Please help. Thanks in advance.
#include <stdio.h>
int main()
{
FILE *f1;
int ch, i, n = 0;
char q[500], opt[4][100];
int corAns;
f1 = fopen("C://Users//Lenovo//Desktop//fileInC1.txt", "a+");
if (f1 == NULL)
{
printf("Error Opening File.");
return 0;
}
else
{
while (n != 2)
{
n++;
printf("\nQuestion: ");
fgets(q, 500, stdin);
for (i = 0; i < 4; i++)
{
printf("\nOption %d: ", i + 1);
fgets(opt[i], 100, stdin);
}
printf("\nCorrect answer: ");
scanf("%d", corAns);
//program terminating here after only one iteration
fprintf(f1, "{\nQ: \"%s\", \n\topt: [\"%s\", \"%s\", \"%s\", \"%s\"], \n\tCA: %d }", q, opt[0], opt[1], opt[2], opt[3], corAns);
printf("\nData Written Successfully.");
}
}
fclose(f1);
return 0;
}
I have been trying to create a Javascript generator as you can see in the code.
The main problem i am getting is inside the while loop.
The while loop is terminating after only one iteration and the program not writting the data in the created file. The file already exists.
I am not getting where is the problem occuring.
You need to cleanse your input of new-lines. You also had a redundant Else statement, and Scanf requires the address of a variable, not it's value.
This should work for you. You can check out this question here: Fgets skipping inputs, which I shamelessly copied.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *f1;
int ch, i, n = 0;
char q[500], opt[4][100];
int corAns;
int c;
char *p;
f1 = fopen("fileInC1.txt", "a+");
if (f1 == NULL)
{
printf("Error Opening File.");
return 0;
}
while (n != 2)
{
n++;
printf("\nQuestion: ");
fgets(q, 500, stdin);
if ((p=strchr(q, '\n')) != NULL) *p = '\0';
for (i = 0; i < 4; i++)
{
printf("\nOption %d: ", i + 1);
fgets(opt[i], 100, stdin);
if ((p=strchr(opt[i], '\n')) != NULL) *p = '\0';
}
printf("\nCorrect answer: ");
scanf("%d", &corAns);
//program terminating here after only one iteration
fprintf(f1, "{\nQ: \"%s\", \n\topt: [\"%s\", \"%s\", \"%s\", \"%s\"], \n\tCA: %d }", q, opt[0], opt[1], opt[2], opt[3], corAns);
printf("\nData Written Successfully.");
while ( (c = getchar()) != '\n' && c != EOF );
}
fclose(f1);
return 0;
}
I am trying to give an if statement to check if a particular name is present in text file, then give access to it otherwise give error message.
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("For person details, please enter the person name: \n");
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
int catch, i=0, index=0;
char ch[100];
printf("Enter your Name: ");
if (scanf("%s", )){ // Don't know what to put here?
perror("Error while reading!");
return 0;
}
catch = fgetc(fr);
while(catch != EOF){
ch[index] = catch;
if (ch[index] == ' '){
ch[index] = '\0';
printf("Here is your result: %s\n",ch);
index = 0;
i++;
}
else
index++;
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
Simply the program firstly opens a file and asks for a user input and verifies if the provided content is case-sensitively matched with the file. If so, then it'll let the program access the entire file and display on the screen, to do that, we must use another FILE b/c the old *fp is already manipulated and in case it's reused, it may display wrong data.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("file.txt", "r"); // for verification
FILE *fp1 = fopen("file.txt", "r"); // for future use
char ch[50], str[50];
short int FLAG = 0;
printf("Enter the string: ");
scanf("%s", &str); // asks for input
while (fscanf(fp, "%s", ch) != EOF) {
if (!strcmp(ch, str)) { // checks if a string matches provided by the user
printf("Found! Here's your details...\n\n");
FLAG = 1;
}
}
if (!FLAG == 1) { // no? exits.
printf("Not found, access denied!\n");
return -1;
}
fclose(fp);
int c = fgetc(fp1); // yes? let's go...
while (c != EOF) {
printf("%c", c); // displays containing data
c = fgetc(fp1);
}
fclose(fp1);
return 0;
}
You'll want to add a variable for your scanf output:
char name[100];
if (scanf("%s", name) != -1)
// ...
Then to compare both you'll use strcmp.
#include <string.h>
//...
if (strcmp(ch, name) == 0)
// both are equal
Note that you can access documentation for scanf and strcmp by typing man scanf or man strcmp in your terminal.
int main()
{
printf("For person details, please enter the person name and id card
number: \n");
printf("Enter your Name: ");
char personName[100];
scanf("%s", personName);
printf("Enter your card number: ");
int cardNumber;
if (scanf("%d", &cardNumber)){
printf("no error detected");
}
else{
printf("error while reading");
}
return 0;
}
The fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
printf("For person details, please enter the person name: \n");
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
int catch, i = 0, index = 0;
char ch[100] = { 0 };
if (fr == NULL)
{
perror("Invalid file opening!");
return 1;
}
printf("Enter your Name: ");
fgets(ch, 100, fr);
size_t len = strcspn(ch, "\n");
ch[(len < 100) ? (len) : (99)] = 0; // For file safety checking
if (strlen(ch)) { // Don't know what to put here?
perror("Error while reading!");
return 1;
}
catch = fgetc(fr);
while (catch != EOF) {
ch[index] = catch;
if (ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your result: %s\n", ch);
index = 0;
memset(ch, 0, 100);
i++;
}
else
{
index++;
}
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
I am writing a program to do this but have error messages. I have changed the fopen-s line to what it is now but this message appears after entering the two file names?
error message
here are no error messages that come up in visual studio but not sure if this is not the problem.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
//setting names of ints and chars.
FILE *file_in;
int wordcount, linecount, charcount;
char letter;
char filename1[50];
char filename2[50];
//setting all counts to 0.
wordcount = 0;
linecount = 0;
charcount = 0;
//Gets the user to enter name of file, then puts it in string.
printf("\n Enter first text document\n");
gets_s(filename1);
printf("\n Enter second text document\n");
gets_s(filename2);
//opens then reads the first file.
fopen_s(&file_in, filename1, "r");
// counts the number of words, then lines, then letters in doc 1.
while ((letter = getc(file_in)) != EOF);
{
if (isspace(letter) && !isspace(getchar()))
{
wordcount++;
}
if (letter == '\n');
{
linecount++;
}
if (letter == '-')
{
charcount++;
}
}
//opens then reads the second file.
fopen_s(&file_in, filename2, "r");
// counts the number of words, then lines, then letters in doc 2.
while ((letter = getc(file_in)) != EOF);
{
if (isspace(letter) && !isspace(getchar()))
{
wordcount++;
}
if (letter == '\n');
{
linecount++;
}
if (letter == '-')
{
charcount++;
}
}
//displays the total on screen.
printf_s("Words:", wordcount, "\n");
printf_s("Letters", charcount, "\n");
printf_s("Lines", linecount, "\n")
}
fopen_s takes 3 arguments. First is pointer, to which you want to assign the file, second is filename and third is how you want to acces file ("r", "w", etc)
A few things I found to change here... This code worked for me:
#include "stdio.h"
#include "stdlib.h"
#include "ctype.h"
int main(int argc, char *argv[])
{
//setting names of ints and chars.
FILE *file_in;
int wordcount, linecount, charcount;
int letter;
char filename1[50];
char filename2[50];
//setting all counts to 0.
wordcount = 0;
linecount = 0;
charcount = 0;
printf("Enter first text document: ");
fgets(filename1, 50, stdin);
ch = filename1;
while(*ch != '\n')
ch++;
*ch = '\0';
printf("Enter second text document: ");
fgets(filename2, 50, stdin);
ch = filename2;
while(*ch != '\n')
ch++;
*ch = '\0';
//opens then reads the first file.
file_in = fopen(filename1, "r");
// counts the number of words, then lines, then letters in doc 1.
while((letter = fgetc(file_in)) != EOF)
{
if (letter == ' ')
{
wordcount++;
}
else if (letter == '\n')
{
linecount++;
}
else
{
charcount++;
}
}
//displays the total on screen.
printf("File 1...\n");
printf("Words: %d\n", wordcount);
printf("Letters: %d\n", charcount);
printf("Lines: %d\n", linecount);
//opens then reads the second file.
file_in = fopen(filename2, "r");
//reset counts
wordcount = 0;
linecount = 0;
charcount = 0;
// counts the number of words, then lines, then letters in doc 2.
while((letter = fgetc(file_in)) != EOF)
{
if (letter == ' ')
{
wordcount++;
}
else if (letter == '\n')
{
linecount++;
}
else
{
charcount++;
}
}
//displays the total on screen.
printf("File 2...\n");
printf("Words: %d\n", wordcount);
printf("Letters: %d\n", charcount);
printf("Lines: %d\n", linecount);
}
With the code below, if I enter 1 string and ctrl-D, it will print did not scan in two words and exit. However if I enter 3 or more strings it takes the first two and throws away the rest. How can I account for this - to make an exit happen if more than two strings are entered?
int scan_count = 0;
printf("Enter two strings: \n");
scan_count = (scanf("%s %s", first_word, second_word));
if (scan_count != 2)
{
printf("Did not scan in two words successfully, exiting.\n");
exit(2);
}
A common usage is to try to read one string more:
char dummy[2];
scan_count = (scanf("%s %s %1s", first_word, second_word, dummy));
But this would only work if you terminate input with Ctrl-D. If you want to know if a line contains exactly 2 words, you must first get the line with fgets and then split it with sscanf:
char line[SIZE], dummy[2];
printf("Enter two strings: \n");
cr = fgets(line, sizeof(line), stdin); /* should test cr againt NULL - omitted for brievety */
if (strchr(line, '\n') == NULL) {
... /* no EOL : line too long*/
}
scan_count = (sscanf("%s %s %1s", first_word, second_word, dummy));
if (scan_count != 2) ...
I know that is ugly but it does the job:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int checkString(char *s1, char *s2){
int c=0,i = 0,j=0,count1 = 0,count2 = 0,res = 0;
while ((c = getchar()) != '\n' && c != EOF){
s1[i++] = (char) c;
if(c ==' '){
count1++;
}
}
s1[i]='\0';
while ((c = getchar()) != '\n' && c != EOF){
s2[j++] = (char) c;
if(c ==' '){
count2++;
}
}
s2[j]='\0';
if((strlen(s1) == 0) || (strlen(s2) == 0)){
return res = 0;
}else if((count1 + count2) == 0){
res = 2;
}
return res;
}
int main(void){
char first_word[50];
char second_word[50];
int scan_count = 0;
printf("Enter any string : ");
if ((scan_count = checkString(first_word,second_word)) != 2){
printf("Did not scan in two words successfully, exiting.\n");
exit(2);
}else{
printf("You typed two strings.\n");
}
return 0;
}
Output1:
Enter any string : michael jackson
michael
Did not scan in two words successfully, exiting.
Output2:
Enter any string : Michael
Jackson
You typed two strings.