i want to make the programm loop again and again until i type the endword ****TELOS
/* 1 */ int text_input();
int main() {
int number;
text_input();
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
printf("Enter the text. (****TELOS for stoping)");
char endword[10];
strcpy(endword, "****TELOS");
char temp[N];
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}
I think your code doesn't work because you don't have set each item of endword to 0
so your code should be like that
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 10
#define M 10
int text_input(char words[M][N]);
int main() {
char a[M][N];
text_input(a);
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
char temp[N];
char endword[10] = {0,0,0,0,0,0,0,0,0,0};
printf("Enter the text. (****TELOS for stoping)");
strcpy(endword, "****TELOS");
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#include<string.h>
typedef struct{
char Mnemonic[7];
int code;
} code;
typedef struct{
char label[10];
unsigned int location;
} symbolTab;
int opLook(char * mnemonic, code * optable)
{
int i = 0;
int value = 0;
for(i ; i<25 ; i++)
{
if(strcmp(mnemonic, optable[i].Mnemonic) == 0)
{
value = optable[i].code;
return value;
}
}
return value;
}
int opValid(char * mnemonic, code * optable)
{
int i = 0;
for(i ; i<25 ; i++)
{
if(strcmp(mnemonic, optable[i].Mnemonic) == 0)
{
return 1;
}
}
return 0;
}
int labelcheck(char * label, symbolTab * Table, int counter)
{
int i = 0;
int flag = 0;
if (counter == 0)
{
return flag;
}
else
{
for(i; i <counter; i ++)
{
if(strcmp(label, Table[i].label) == 0)
{
flag = 1;
}
}
return flag;
}
}
unsigned int labelVal(char * label, symbolTab * Table, int counter)
{
int i = 0;
for(i; i <counter; i ++)
{
if(strcmp(label, Table[i].label) == 0)
{
return Table[i].location;
}
}
}
void Assemble(char* filename)
{
unsigned int locctr = 0; /*location counter*/
unsigned int prolen = 0; /*program length*/
int mnemoVal; /*mnemonic Value in Int*/
int labelctr = 0;
code Opta[25] = {{"ADD", 24},{"AND",88},{"COMP",40},{"DIV",36},{"J",60},
{"JEQ",48},{"JGT",52},{"JLT",56},{"JSUB",72},{"LDA",00},
{"LDCH",80},{"LDL", 8},{"LDX", 4},{"MUL",32},{"OR",68},
{"RD",216},{"RSUB",76},{"STA",12},{"STCH",84},{"STL",20},
{"STX",16},{"SUB",28},{"TD",224},{"TIX",44},{"WD",220}};
symbolTab symTab[500];
char buffer[255];
FILE * source;
FILE * interFile;
FILE * objF;
FILE * ListFile;
interFile = fopen("intermidiateFile.txt", "w+");
ListFile = fopen("ListingFile.txt", "w+");
objF = fopen("ObjectFile.txt", "w+");
source = fopen("source.txt", "r");
char * lab; /*label*/
char * mnemo; /*mnemonic*/
char * operand;
char * address = "adress";
unsigned int opeaddress;
fgets(buffer, 255, source);
if (buffer[0] != '.')
{
fprintf(interFile, "%s", buffer);
}
/*Getting first line and initialization of Location Counter*/
if(buffer[0] == '.') /* if the line is a comment continue with the next iteration of the loop*/
{
locctr = 0;
}
else
{
if(buffer[0] == ' ' || buffer[0] == '\t')
{
mnemo = strtok(buffer, " \t");
operand = strtok(NULL, " \t");
if(strcmp(mnemo, "START") == 0)
{
locctr = strtol(operand, NULL, 16);
}
else
{
/*error*/
}
}
else
{
lab =strtok(buffer, " \t");
mnemo = strtok(NULL, " \t");
operand = strtok(NULL, " \t");
if(strcmp(mnemo, "START") == 0)
{
locctr = strtol(operand, NULL, 16);
}
else
{
/*error*/
}
}
}
/* End of the location counter initialization */
/*start while loop*/
while(!feof(source))
{
memset(lab, '\0', strlen(lab));
memset(mnemo, '\0', strlen(mnemo));
memset(operand, '\0', strlen(operand));
fgets(buffer, 255, source);
fprintf(interFile, "%s", buffer);
if(buffer[0] == '.') /* if the line is a comment continue with the next iteration of the loop*/
{
continue;
}
else /* Else for... If it is not a comment, then check if it start with a character or a space*/
{
if(buffer[0] == ' ' || buffer[0] == '\t') /* If it start with a space, then it is just a mnemonic or mnemonic & operand*/
{
mnemo = strtok(buffer, " \t\n\r");
if (strcmp(mnemo, "END") == 0)
{
break;
}
if(strcmp(mnemo, "RSUB") == 0)
{
mnemoVal = opLook(mnemo, Opta);
fprintf(interFile, "%x %02x\n", locctr, mnemoVal);
}
else
{
operand = strtok(NULL, " \t\r\n");
mnemoVal = opLook(mnemo, Opta);
fprintf(interFile, "%x %02x %s\n", locctr, mnemoVal, operand);
}
}
else
{
lab = strtok(buffer, " \t\n\r"); /* it has a label, mnemonic and operand*/
if(labelcheck(lab, symTab, labelctr) == 0) /* check if the label is already in the symTab, if not, add it, otherwise it is an error*/
{
strcpy(symTab[labelctr].label, lab);
symTab[labelctr].location = locctr;
labelctr++;
mnemo = strtok(NULL, " \t\n\r");
if (strcmp(mnemo, "END") == 0)
{
break;
}
operand = strtok(NULL, " \t\n\r");
mnemoVal = opLook(mnemo, Opta);
}
else
{
mnemo = strtok(NULL, " \t\n\r");
if (strcmp(mnemo, "END") == 0)
{
break;
}
operand = strtok(NULL, " \t\n\r");
mnemoVal = opLook(mnemo, Opta);
}
fprintf(interFile, "%x %s %02x %s\n", locctr, lab, mnemoVal, operand);
}
}
if(strcmp(mnemo, "WORD") == 0 )
{
locctr = locctr + 3;
}
else if(strcmp(mnemo, "BYTE") == 0 )
{
unsigned int val;
if (operand[0] =='C')
{
val = strlen(operand) - 3;
locctr = locctr + val;
}
else
{
val = (strlen(operand) - 3)/2;
locctr = locctr + val;
}
}
else if(strcmp(mnemo, "RESB") == 0)
{
locctr = locctr + atoi(operand);
}
else if(strcmp(mnemo, "RESW") == 0)
{
locctr = locctr + (3*atoi(operand));
}
else
{
locctr= locctr + 3;
}
}
/* End of While loop*/
prolen = locctr - symTab[0].location;
fprintf(interFile, "\n%x", prolen);
fclose(source);
fclose(interFile);
interFile = fopen("intermidiateFile.txt", "r");
/*Start the Listing File and Object File ---------------------Pass 2----------- */
fgets(buffer, 255, interFile);
if(buffer[0] == '.') /* if the line is a comment continue with the next iteration of the loop*/
{
locctr = 0;
/*Error missung Start or Misplaced*/
}
else
{
if(buffer[0] == ' ' || buffer[0] == '\t')
{
mnemo = strtok(buffer, " \t");
operand = strtok(NULL, " \t");
if(strcmp(mnemo, "START") == 0)
{
locctr = strtol(operand, NULL, 16);
strcpy(address, operand);
fprintf(ListFile, "%X %s %s\n", locctr, mnemo, operand);
}
else
{
/*error*/
}
}
else
{
lab =strtok(buffer, " \t");
mnemo = strtok(NULL, " \t");
operand = strtok(NULL, " \t");
if(strcmp(mnemo, "START") == 0)
{
locctr = strtol(operand, NULL, 16);
fprintf(ListFile, "%x %s %s %s\n", locctr, lab, mnemo, operand);
fprintf(objF, "H%s__%06x%06x\n", lab, locctr, prolen);
}
else
{
/*error*/
}
}
}
while(!feof(interFile))
{
memset(lab, '\0', strlen(lab));
memset(mnemo, '\0', strlen(mnemo));
memset(operand, '\0', strlen(operand));
memset(address, '\0', strlen(address));
memset(buffer, '\0', strlen(buffer));
fgets(buffer, 255, interFile);
if (buffer[0] == '\r')
{
continue;
}
if(buffer[0] == ' ' || buffer[0] == '\t')
{
mnemo = strtok(buffer, " \t\n\r");
if (strcmp(mnemo, "END") == 0)
{
break;
}
if(strcmp(mnemo, "RSUB") == 0)
{
memset(buffer, '\0', strlen(buffer));
fgets(address, 255, interFile);
mnemoVal = opLook(mnemo, Opta);
fprintf(ListFile, "%s %s %X0000", address, mnemo, mnemoVal);
}
else
{
operand = strtok(NULL, " \t\r\n");
mnemoVal = opLook(mnemo, Opta);
memset(buffer, '\0', strlen(buffer));
fgets(address, 255, interFile);
if (labelcheck(operand, symTab, labelctr) == 1)
{
opeaddress = labelVal(operand, symTab, labelctr);
}
else
{
opeaddress = 0;
/* error*/
}
fprintf(ListFile, "%s %s %s %02X%04X", address, mnemo, operand, mnemoVal, opeaddress);
}
}
else if (buffer[0] == '.')
{
fprintf(ListFile, "%s\n", buffer);
}
else
{
lab = strtok(buffer, " \t\n\r");
mnemo = strtok(NULL, " \t\n\r");
operand = strtok(NULL, " \t\n\r");
mnemoVal = opLook(mnemo, Opta);
memset(buffer, '\0', strlen(buffer));
fgets(address, 255, interFile);
if (labelcheck(operand, symTab, labelctr) == 1)
{
opeaddress = labelVal(operand, symTab, labelctr);
}
else
{
opeaddress = 0;
/* error*/
}
fprintf(ListFile, "%s %s %s %s %02X%04X", address, lab, mnemo, operand, mnemoVal, opeaddress);
}
}
fclose(interFile);
fclose(objF);
fclose(ListFile);
}
The error occurs in the last while loop when executing fgets();
I have looked if I had any variable or syntax wrong, but everything looks fine.
This is a part of a two pass assemble. The error varies between the fgets in the last while loop. At first I thought that it was the memset function, but the error still happened when I mark them as comments
Because of
char * address = "adress";
address is pointing to Read Only Memory
Trying to modify string literals (in your case "adress") invokes undefined behavior.
Then in your last loop
strcpy(address, operand);
memset(address, '\0', strlen(address));
fgets(address, 255, interFile);
Are wrong.
You could change that variable to a simple array of chars with enough room for your needs, e.g.:
char address[128];
I am currently writing a shell for school purposes and I have the problem that if I write the command "history", the "exit" command afterwards doesn't work. If you could help me I would be very happy.
Here is my code:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#define MAX_INPUT 256
static char cwd[100];
void myprintf(char *text) {
text != NULL ?
printf("%s#rash:%s: %s\n", getenv("USER"), getcwd(cwd, sizeof(cwd)), text) :
printf("%s#rash:%s: ", getenv("USER"), getcwd(cwd, sizeof(cwd)));
}
void errprintf(char *text) {
myprintf(NULL);
printf("Couldn't run %s\n", text);
}
static char *argv[256];
static int argc;
static int pid = 0;
FILE *fhistory;
void parseInput(char *input) {
input = strtok(input, "\n");
for (argc = 0; argc < MAX_INPUT; argc++) {
argv[argc] = NULL;
}
argc = 0;
fprintf(fhistory, "%s\n", input);
char *param = strtok(input, " ");
while (param) {
argv[argc++] = param;
param = strtok(NULL, " ");
}
}
void signalHandler(int sign) {
switch (sign) {
case SIGINT: {
if (pid != 0) {
kill(pid, SIGKILL);
pid = 0;
}
break;
}
case SIGCHLD: {
if (pid != 0) {
kill(pid, SIGKILL);
pid = 0;
}
break;
}
}
}
int programs() {
if (!strcmp(argv[0], "exit")) {
return -1;
}
if (!strcmp(argv[0], "cd")) {
chdir(argv[1] == NULL ? getenv("HOME") : argv[1]);
} else {
pid = fork();
switch (pid) {
case -1: {
myprintf("Erectile Dysfunction!");
break;
}
case 0: {
if (!strcmp(argv[0], "history")) {
system("cat .rash_history.txt");
} else {
execvp(argv[0], argv);
errprintf(argv[0]);
}
break;
}
default: {
waitpid(pid, NULL, 0);
signal(SIGCHLD, signalHandler);
return 0;
}
}
}
return 1;
}
int main(void) {
signal(SIGINT, signalHandler);
char *input = NULL;
myprintf("Welcome to rash!");
fhistory = fopen(".rash_history.txt", "a");
while (input != NULL ? strncmp(input, "exit", strlen(input)) != 0 : 1) {
myprintf(NULL);
input = (char *) malloc(sizeof(char *) * MAX_INPUT);
int j;
for (j = 0; j < MAX_INPUT; j++) {
input[j] = '\0';
}
fgets(input, MAX_INPUT, stdin);
parseInput(input);
if (*(input) != '\n') {
programs();
}
}
fclose(fhistory);
return 0;
}
I think here while (input != NULL ? strncmp(input, "exit", strlen(input)) != 0 : 1) {
it would be strlen("exit")
The "input" variable take value inside your while loop only:
fgets(input, MAX_INPUT, stdin);
parseInput(input);
The parseInput uses strtok function couple times. The strtok modifies the argument string, so it not clear what value it will contains at time you will compare it with "exit".
Try to duplicate "input" string before calling strtok. Try to add debug string at the end of loop to make clear what value is into input string.
Below is the code template and under /* write your code here */ is my own code.
The template should be correct but there is sth wrong with my code.
My algorithm is to iterate through str until finding the null character.
Then compare each character, if they are the same then iterate through both str and sub, otherwise set continue to iterate through str and reset to the first character of substr.
#include <stdio.h>
int findSubstring(char *str, char *substring);
int main()
{
char str[40], substr[40];
printf("Enter the string: ");
gets(str);
printf("Enter the substring: ");
gets(substr);
printf("findSubstring(): %d\n", findSubstring(str, substr));
return 0;
}
int findSubstring(char *str, char *substr)
{
/* write your code here */
int i = 0, j = 0;
while ((str[j] != '\0')||(substr[i] != '\0')) {
if (substr[i] != str[j]) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (substr[i] == '\0')
return 1;
else
return -1;
}
Do not use gets(), which has unavoidable risk of buffer overrun.
The condition of the loop is wrong. The loop should exited if one of *(str + j) or *(substr + i) is a (terminating) null character.
Fixed code:
#include <stdio.h>
int findSubstring(char *str, char *substring);
void safer_gets(char *str, size_t max);
int main(void)
{
char str[40], substr[40];
printf("Enter the string: ");
safer_gets(str, sizeof(str));
printf("Enter the substring: ");
safer_gets(substr, sizeof(str));
printf("findSubstring(): %d\n", findSubstring(str, substr));
return 0;
}
int findSubstring(char *str, char *substr)
{
int i = 0, j = 0;
while ((*(str + j) != '\0')&&(*(substr + i) != '\0')) {
if (*(substr + i) != *(str + j)) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (*(substr + i) == '\0')
return 1;
else
return -1;
}
void safer_gets(char *str, size_t max)
{
int i;
fgets(str, max, stdin);
for (i = 0; *(str + i) != '\0'; i++) {
if (*(str + i) == '\n') {
*(str + i) = '\0';
break;
}
}
}
/*--------------------------One more simple example-----------------------------
Find the words from a set of words containing a given substring?
Input: Set of Words: [blackcat, blackdog, blackrat, whitetiger, blueelephant],
Substring: black
Output:[blackcat, blackdog, blackrat]
-----------------------------------------------------------------------------------------*/
#include <iostream>
#include <cstring>
int substring(char* sub,char* string);
int main()
{
const char* Names[] { "blackcat", "blackdog", "blackrat", "whitetiger", "blueelephant" };
char substr[]{ "black" };
int found{ -1 };
for (auto strings: Names)
{
found = substring(substr, const_cast<char*>(strings));
if (found != -1) {
std::cout << strings << " ";
}
}
std::cout << std::endl;
return 0;
}
int substring(char* sub, char* string)
{
int i{};
int j{};
while ((string[i] != '\0') && (sub[j] != '\0'))
{
if (string[i] != sub[j]) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (sub[j] == '\0' && i != 0) {
return 1;
}
else {
return -1;
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s[100],sub[50];
int i,j,c=0;
clrscr();
printf("enter string and substring\n");
gets(s);
printf("\n");
gets(sub);
printf("\n");
i=0;
j=0;
while(s[i]!='\0')
{
if(s[i]!=sub[j])
i++;
else if(s[i]==sub[j])
{
while(sub[j]!='\0')
{
if(s[i]==sub[j])
{
i++;
j++;
c++;
}
else
{
c=0;
break;
}
}
}
}
if(c!=0)
printf("\nsubstring is present \n ");
else
printf("\nsubstring is absent \n ");
getch();
}
I need to convert infix to postfix and evaluate postfix expression. When reading from a file, I should be able to evaluate multiple expressions at once. But when I run it and it encounters an expression that is not well-formed in the sense that there are more closed parentheses than open ones, it evaluates that expression 2 or 3 times.
Code:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX 1000
typedef struct stack
{
int data[MAX];
int top;
} stack;
int priority(char);
void init(stack*);
int empty(stack*);
int full(stack*);
char pop(stack*);
void push(stack*, char);
char top(stack*);
void add(char*, char, int);
void keyboard();
void read_file();
int change(char);
void pushYO(double);
double popYO();
stack s;
char x;
int i, token, topYO = -1;
double result[MAX];
char filepath[MAX];
int main()
{
char choice;
init(&s);
system("CLS");
printf("[1] Keyboard \n[2] Read from text file \n[3] Exit \n");
scanf("%c", &choice);
if(choice != '1' && choice != '2' && choice != '3')
{
main();
}
else if(choice == '1')
{
keyboard();
}
else if(choice == '2')
{
read_file();
}
else if(choice == '3')
{
printf("\nThank you for using Kei Shirabe's \ninfix to postfix converter and evaluator! :)\n");
exit(0);
}
}
void keyboard() //the keyboard input version. this works fine
{
//code here
}
void read_file()
{
int z, count, form, paren;
double one, two, three = 1;
char infx[MAX];
char pofx[MAX];
char choice;
FILE *text = fopen("text.txt", "a");
printf("Enter path of file:");
scanf("%s",&filepath);
FILE *textYO = fopen(filepath, "r");
if((textYO) == NULL)
{
printf("\nError! Unable to open %s\n\n", filepath);
}
else
{
while((fgets(infx, MAX, textYO))!= NULL)
{
form = -1, paren = 0, count = 0, z = 0;
infx[
strlen(infx)-1] = '\0';
for (i=0; i<strlen(infx); i++)
{
if((token = infx[i]) != '\n')
{
if(isalnum(token))
{
form++;
}
else
{
if(token == '(')
{
paren++;
}
else if(token == ')')
{
paren--;
}
else
{
form--;
}
}
if (paren < 0)
{
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nError! Not well formed :( \n-----------------\n");
fprintf(text, "\n\nError! Not well formed :( \n-----------------\n");
}
else
if(isalnum(token))
{
add(pofx, token, count);
count++;
}
else
if(token == '(')
{
push(&s, '(');
}
else
{
if(token == ')')
while((x = pop(&s)) != '(')
{
add(pofx, x, count);
count++;
}
else
if(token == '^')
{
push(&s, token);
}
else
{
while(priority(token) <= priority(top(&s)) && !empty(&s))
{
x = pop(&s);
add(pofx, x, count);
count++;
}
push(&s, token);
}
}
}
else
{
while(!empty(&s))
{
x = pop(&s);
add(pofx, x, count);
count++;
}
}
}
if(form != 0 || paren != 0)
{
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nError! Not well formed :( \n-----------------\n");
fprintf(text, "\n\nError! Not well formed :( \n-----------------\n");
}
else
{
form = -1, paren = 0;
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nPostfix: %s \n\n", pofx);
fprintf(text, "\n\nPostfix: %s\n\n", pofx);
while((token = pofx[z++]) != '\0')
{
three = 1;
if(!isdigit(token) && !isalpha(token))
{
two = popYO();
one = popYO();
switch(token)
{
case '+':
pushYO(one+two); break;
case '-':
pushYO(one-two); break;
case '*':
pushYO(one*two); break;
case '/':
pushYO(one/two); break;
case '^':
if (two > 0)
{
for(i=0;i<two;i++)
{
three = three * one;
}
pushYO(three);
three = 1; break;
}
else
{
for(i=0;i<(two-(2*two));i++)
{
three = three * one;
}
pushYO((1/three));
three = 1; break;
}
}
}
else if(isalpha(token))
{
if(isupper(token))
{
pushYO(token - '#');
}
if(islower(token))
{
pushYO(token - change(token));
}
}
else
{
pushYO(token - '0');
}
}
printf("Result: %lf\n-----------------\n", result[topYO]);
fprintf(text, "Result: %lf\n-----------------\n", result[topYO]);
}
}
}
fclose(text);
fclose(textYO);
printf("\nRun again? \n[1] Yes \n[any other key] No\n");
scanf("%c", &choice);
scanf("%c", &choice);
if(choice == '1')
{
main();
}
else
{
printf("\nThank you for using Kei Shirabe's \ninfix to postfix converter and evaluator! :)\n");
exit(0);
}
}
//other functions down here, not important
Sample text file (and yes there is an extra space at the end):
(1+2))
(1+2*3)
For this text file, the expression (1+2)) is evaluated three times, each result being "Not well formed". The last expression works as expected.
Any help please?