While loop not going back into loop - loops

I have been working on a project and I'm almost finish the last problem I have is creating a while loop that keeps asking the user if they want to convert an expression. So far it does it once then doesn't continue asking. I know this is a simple question and I think I have the logic down but for some reason it isn't working.
Here is my main:
int main(){
string answer=" ";
string expression;
while(answer!="no"){
cout<<"Would you like to do a conversion,type yes or no:";
getline(cin,answer);
cout<<" Enter a Post Fix expression:";
getline(cin,expression);
convert(expression);
}
return 0;
}
Though not really necessary for my question here is the code above my main in case it is useful:
/*
* PLEASE DO NOT PLACE A SPACE BEFORE YOU INPUT THE FIRST OPERAND
*
*
*/
#include "stack.h"
void convert(string expression){
stack k; //Stores raw input string
stack c; //stores input string without spaces
stack s;//stores the string values
string post =" ";
string rightop="";
string leftop="";
string op ="";
int countop=0;// counts the number of operators
int countoper=0;// counts the number of operands
for (int i =0; i<=expression.length()-1;i++){
k.push(expression[i]);
if(expression[i] == '*' ||
expression[i] == '+' ||
expression[i] == '-' ||
expression[i] == '/')
{
countop++;
}
}
c.push(expression[0]);
int count=expression.length()/2;
countoper=(count-countop)+1;
if (countop==countoper){ //tells when there are too many opertors and not enough operands
cout<<"too many operators and not enough operand"<<endl;
exit(1);
}
if(countop==countoper*2){ //tells when there are too many opertors and not enough operands
cout<<"too many operands and not enough operators"<<endl;
exit(1);
}
for(int i=1;i<=expression.length()/2;i++){
c.push(expression[2*i]);
}
for(int i=0; i<2;i++){
leftop=c.top();
c.pop();
rightop=c.top();
c.pop();
op=c.top();
c.pop();
post="(" + leftop + " " + op + " " + rightop + ")";
s.push(post);
if(count<6){
cout<<s.top()<<endl;
}
}
if (count>=6){
cout<<"(";
cout<<s.top();
cout<<c.top();
s.pop();
cout<<s.top();
cout<<")";
}
}

I tried this code, which I copied from yours, and it worked fine. Which made me arrive to the conclusion that I do not understand what the problem is or what you want.
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(){
string answer=" ";
string expression;
while(answer!="no"){
cout<<"Would you like to do a conversion,type yes or no:";
getline(cin,answer);
cout<<" Enter a Post Fix expression:";
getline(cin,expression);
// do something
}
return 0;
}
What this is doing:
1) user answers "no" to first question, then user writes something on the second input. Exits program.
2) user answers something different from "no", then user writes something. Goes back to the first question.
What is the behaviour that you want? Explain better.

I also ran your code and the while loop worked for me.
Perhaps you can begin by commenting out your convert(expression); call and debugging from there!
#include <iostream>
using namespace std;
int main(){
string answer=" ";
string expression;
while(answer!="no"){
cout<<"Would you like to do a conversion,type yes or no:";
getline(cin,answer);
cout<<" Enter a Post Fix expression:";
getline(cin,expression);
/*convert(expression);*/
}
return 0;
}

Related

compare string with type of variables

Hello im in need of some help this part of my program is to get a input string like 2x³+2y² and separate it in 2 arrays termos=terms and exp=exponential, however i cant seem to get it working
#include <stdio.h>
#include <math.h>
int main()
{
char poly[50];
int termos[10];
int exp[10];
int contt=0, conte=0, i=0;
char var1, var2, var3;
printf("Introduza o polinómio\n");
scanf("%s", &poly);
for(i=0; i<50; i++)
{
if(poly[i-1]==char && poly[i]==int && poly[i-1]!='+')
{
exp[conte]=poly[i];
conte++;
}
if(poly[i]==int)
{
termos[contt]=poly[i];
contt++;
}
if(poly[i]=='x')
var1=poly[i];
if(poly[i]=='y')
var2=poly[i];
if(poly[i]=='z')
var3=poly[i];
}
Simply impossible, there is not runtime type information in c. Perhaps you should read The XY Problem and ask another question later.
In the line
if(poly[i-1]==char && poly[i]==int && poly[i-1]!='+')
you want to know if poly[i-1] is an alphabetic character, e.g. an 'a', or is a number. You can use the following functions from ctype.h for that:
// among the includes
#include <ctype.h>
// later
if(isalpha(poly[i-1]) && isdigit(poly[i]) && poly[i-1]!='+')
There are more problems in your code. We will post these as comments.

C - Linked List Segmentation Fault During Display

Edit 2: I realized that I did not have a "Not found" result for any query not in the database. Changes have been made to introduce this feature. Here is the current test and test output:
Input:
3
sam
99912222
tom
11122222
harry
12299933
sam
edward
harry
Output:
Not found
=0
Not found
=0
Not found
=0
Not found
=0
sam
=99912222
Not found
=0
Not found
=0
Not found
[Infinite loop continues]
Edit: I have changed a few things in the while loop in display(). I am now getting an infinite loop printing "=0" except for the third or fourth cycle through the search. Hmmm...
By the way, thanks for the reminder of testing strings with ==. Seems like a no-brainer now.
I have done some searching and have yet to be able to understand where I have gone wrong with my code. I am working on a challenge which will result in a simple phone-book program. It will take input of a number (the number of entries to be added) then the names and associated phone numbers (no dashes or periods). After the entries have been added then the user can search for entries by name and have the number displayed in the format "name=number".
The code throws a segmentation fault with the while loop in the display() function. I assume that I am attempting to print something assigned as NULL, but I cannot figure out where I have gone wrong. Any help would be very appreciated.
Lastly, the challenge calls for me to read queries until EOF; however, this confuses me since I am to accept user input from stdin. What does EOF look like with stdin, just a register return (\n)?
(PS: This is my first attempt at linked lists, so any pointers would be greatly appreciated.)
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void add_entry(void);
void display(void);
struct phonebook {
char name[50];
int number;
struct phonebook *next;
};
struct phonebook *firstp, *currentp, *newp;
char tempname[50];
int main() {
int N;
firstp = NULL;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
add_entry();
}
display();
return 0;
}
void add_entry(void) {
newp = (struct phonebook*)malloc(sizeof(struct phonebook));
if (firstp == NULL) firstp = currentp = newp;
else {
currentp = firstp;
while (currentp->next != NULL)
currentp = currentp->next;
currentp->next = newp;
currentp = newp;
}
fgets(currentp->name, 50, stdin);
scanf("%d", &currentp->number);
currentp->next = NULL;
}
void display(void) {
while (strcmp(tempname, "\n") != 0) {
currentp = firstp;
fgets(tempname, 50, stdin);
while (strcmp(currentp->name, tempname) != 0) {
if (currentp->next == NULL) {
printf("Not found\n");
break;
}
currentp = currentp->next;
}
printf("%s=%d\n", currentp->name, currentp->number);
}
}
Your problem is that you never find the entry you're looking for. The expression currentp->name != tempname will always be true, since those are always unequal. In C, this equality test will not compile into a character-by-character comparison, but into a comparison of pointers to currentp->name and tempname. Since those are never at the same addresses, they will never be equal.
Try !strcmp(currentp->name, tempname) instead.
The reason you crash, then, is because you reach the end of the list, so that currentp will be NULL after your loop, and then you try to print NULL->name and NULL->number, actually causing the crash.
Also, on another note, you may want to start using local variables instead of using global variables for everything.
Not sure if this solves the problem, but you can't directly compare strings with != in C. You need to use if( strcmp( string1, string2 ) == 0 ) to check.
fgets doesn't take EOF (= -1) like getchar does, but it does include '\n' and pad the rest with NULL (= 0) so checking for EOF is not really helpful, but yes you can stop after \n or NULL.

Debug assertion failed fprintf in VS 2010

I'm new in programming and iam from Tver.
There is a problem in program. I don't know where. I am using input file and output file. So, i tried to debug program, but i failed
I'm using a Visual Studio 2010.
Thank you in advance.
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string.h>
using namespace std;
int num[100];
void outc(int s, int ss)
{int i,temp,numb[100],k,l,t;
temp=s; i=0;
while (temp>0)
{
numb[i]=temp%ss;
if (numb[i]>=10) numb[i]='A'-10+temp%16;
temp/=ss;
i++;}
l=i/2; t=0;
i--;
while (i>=l)
{
k=numb[t];
numb[t]=numb[i];
numb[i]=k;
t++;
i--;
}
FILE* fooo;
errno_t errorCodes=fopen_s(&fooo,"output.txt","w");
fprintf(fooo,"s%d= %d\n", ss, numb);
return;
}
int main()
{char c,strbuf[100],num[100];
char *res;
int k,s,i,temp,ost,s2,s8,s10,s16;
FILE* foo;
errno_t errorCode=fopen_s(&foo,"input.txt","r");
fgets(strbuf,1000,foo);
if(strbuf[strlen(strbuf)-1]=='b')
{
strncpy_s(strbuf, strbuf, strlen(strbuf)-1);
c=atoi(strbuf);
k=0;s=0;
while(c!=0)
s+=(c%10)*pow(2,k);
c/=10;
k++;
} else
if(strbuf[0]==0 && strbuf[1]!='x')
{i=0;;
do{
strbuf[i]=strbuf[i+1];
i++;
}while(i!=strlen(strbuf)-1);
c=atoi(strbuf);
k=0;s=0;
while(c!=0)
s+=(c%10)*pow(8,k);
c/=10;
k++;
} else
if(strbuf[0]=='0' && strbuf[1]=='x')
{i=0;k=strlen(strbuf);
do{
strbuf[i]=strbuf[i+2];
i++;
}while(i!=k);
puts(strbuf);
k=0;s=0;
for (i=strlen(strbuf)-1;i>=0; i--)
{
if (strbuf[i]>='A' && strbuf[i]<='F')
c=10+strbuf[i]-'A'; else c=strbuf[i]-'0';
printf("%d\n",c);
s+=c*pow(16,k);
k++;
}
} else s=atoi(strbuf);
printf("%d\n",s);
outc(s,2);
outc(s,8);
FILE* fooo;
errno_t errorCodep=fopen_s(&fooo,"output.txt","w");
fprintf(fooo,"s10= %d\n", s);
outc(s,16);
//if (temp%16>=10) num[len-1]='A'-10+temp%16;
//printf("s2= %d\ns8= %d\ns10= %d\ns16= %d\n", s2, s8, s, s16);
_getch();
return 0;
}
This has numerous issues:
You can't #include <iostream> or have using namespace std in a C program.
There are so many compiler specific things in here that it's going to be hard for most people to help you. You'll make your life a lot easier by writing in standard C. There's no way for me to compile this program to check what's wrong with it, for instance.
Your code is very hard to follow when you use variable names like k, and s, and s2, and the like, and do things like FILE * foo followed by FILE * fooo. Your code is also just formatted horribly.
With strncpy_s(strbuf, strbuf, ...) unless Microsoft is doing something really weird, here, you can't specify the same string as both the source and destination.
strtol() is better here than atoi().
You're not closing any of the files you open, and you're not checking whether they did, in fact, open. Using the & operator here: errorCode=fopen_s(&foo, ... is highly suspicious, but again, you're using some non-standard function, so who knows.
Here: fprintf(fooo,"s%d= %d\n", ss, numb) you tell fprintf() to expect two ints, but the last argument is an array.

short function in c - don't understand what's wrong

I'm writing a function that just calculates the "complementary" strand of DNA, meaning replaces C with G, T with A, and so on.
this is what I wrote:
#include <stdio.h>
#include <string.h>
#define SIZE 70
int isLegitSequence(char sequence[]);
void getComplementaryStrand(char complementary[],char sequence[]);
int findSubSequence(char sequence[],char subsequence[]);
int findSubComplementary(char sequence[],char subcomplementary[]);
void cutSequence(char sequence[],char tocut[]);
void checkDNAList(char data[][SIZE],int rows,char sequence[]);
void main(){
char dnaSequence[SIZE];
char compDnaSequence[SIZE];
printf("Enter a DNA Strand\n");
gets(dnaSequence);
printf("%d\n",isLegitSequence(dnaSequence));
getComplementaryStrand(compDnaSequence,dnaSequence);
puts(compDnaSequence);
}
int isLegitSequence(char sequence[]){
int i=0;
while (sequence[i]){
if(sequence[i]=='A'||sequence[i]=='C'||sequence[i]=='G'||sequence[i]=='T');
else return 0;
i++;
}
return 1;
}
void getComplementaryStrand(char complementary[SIZE],char sequence[SIZE]){
int j=strlen(sequence)-1,i;
for(i=0;sequence[i];i++,j--){
if(sequence[i]=='A') sequence[j]='T';
else if(sequence[i]=='C') sequence[j]='G';
else if(sequence[i]=='G') sequence[j]='C';
else sequence[j]='A';
}
complementary[strlen(sequence)]='\0';
}
However, this is what I get when I run the program:
Enter a DNA Strand
CGCTC
1
╠╠╠╠╠
Press any key to continue . . .
This is my first time using functions, so I'm not sure what I did wrong here.
Would appreciate help, but in the scope of my understanding, namely very very basic.
You need to add a prototype of the function getComplementaryStrand at the top of of the source file where the function is called.
Add this line at the top of the source file:
void getComplementaryStrand(char complementary[SIZE],char sequence[SIZE]);
EDIT: the question has changed in the meantime... Before it was a compilation error. OP please ask a new question instead of editing your original question with a new question.
Take a careful look at your for loop within your getComplementaryStrand() function. Are you assigning values to the correct string? I think not.
In getComplementaryStrand() you never fill anything in complementary string except end character. So you get garbage.

Creating a terminal menu with a challenge

What I wont to do is to create a terminal menu that takes various types of arguments and place it in a array param. Under is the code: Here is some trouble that I have and cant find a good solution for.
if i just type 'list' I will get Not a valid command, I have to type “list “ (list and space).
Menu choice new should be like this: new “My name is hello”. param[0] = new and param[1] = My name is hello , (sow I can create a message with spaces).
How can I accomplish this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
int menu()
{
printf(">");
char line[LINE_MAX];
int i = 0;
char *param[4];
while(fgets(line, LINE_MAX, stdin) != NULL) {
param[i++] = strtok(line, " \n");
if(param[0] != NULL) {
char *argument;
while((argument = strtok(NULL, "\n")) != NULL) {
param[i++] = argument;
}
}
if(strcmp(param[0], "new") == 0) {
//new(param[1]);
menu();
} else if(strcmp(param[0], "list") == 0) {
//list();
menu();
} else {
printf("Not a valid command.\n\n");
menu();
}
}
return 0;
}
You're delimiting on " ".
fgets reads the ENTER.
So, when you type "listENTER" and tokenise at spaces you get one token, namely "listENTER". Later you compare with "list" and, of course, it doesn't match.
Try
strtok(line, " \n"); /* maybe include tabs too? */
PS. Why are you calling menu recursively? You already have a while in the function ...
Your problem is param[i++] = strtok(line, " "); will only split on space, not on \n (newline). Try adding this to your array of delimeters.
Oh, and congratulations for some decent looking code that's clean and well formatted. A pleasant change.
I'm not sure if this causes your problem but these lines
/*new(param[1]);
/*list();
Start a comment that is never terminated.
If you want one line comments you can use:
// comment
(atleast in C++ and from C99 on)
But comments starting with /*must be ended with a */and not nested:
/* comment */
/* also multi line
allowed */
Since you start a comment in a comment your compiler should have emmited a warning, actually this shouldn't compile at all.
The reason you need to type "list " is that your first strtok tokenizes until a space character, so you need to enter one in this case. Try allowing both '\n' and space as separators, i.e. replace the second parameter of strtok with " \n".
As for quotes, you need to re-combine parameters starting from the one beginning with a quote to the one ending with one by replacing the characters in between them with spaces. Or do away with strtok and parse by manually iterating through the characters in line.

Resources