My while loop does not work - visual-c++

i want to check the user input which cant larger than 2 and smaller than 1 as well as cant be char (because the input type is int) but my code seem not working.....anyone can help me out? I tried various way but seem i still get it
update: here is part the code , source is declared as int in previous part
Student stu;
List<Student> list;
char id[10];
string str;
int choice;
int source;
bool ask;
while(true){
switch(menu()) {
case 1:
{
system("cls");
if (ReadFile("student.txt", &list)) {
cout << "\nRead File Successfully!\n";
}
else
cout << "\nRead File Failed!\n";
system("pause");
break;
}
case 2:
{
system("cls");
if(list.empty()){
cout<<"\nThe list is empty!\n";
break;
}
cout<<"\nStudent id: ";
getline(cin,str);
while(!isdigit(str)){
cout<<"\nEnter [x] back to menu or re-enter the student id: ";
getline(cin,str);
if(str=="x"||str=="X"){
break;
}
}
strcpy_s(id,10,str.c_str());
if(DeleteRecord(&list, id)){
cout<<"\nStudent successfully deleted!\n";
}
else
cout<<"\nDelete student record failed!\n";
system("pause");
break;
}
case 3:
{
system("cls");
if(list.empty()){
cout<<"\nThe list is empty!\n";
break;
}
cout<<"\nStudent id: ";
getline(cin,str);
while(!isdigit(str)){
cout<<"\nEnter [x] back to menu or re-enter the student id: ";
getline(cin,str);
if(str=="x"||str=="X"){
break;
}
}
strcpy_s(id,10,str.c_str());
if(SearchStudent(&list, id, stu)){
cout<<"\nStudent record found!\n";
}
else
cout<<"\nStudent record not found!\n";
system("pause");
break;
}
case 4:
{
system("cls");
/*if(InsertResult("exam.txt",&list)) //Call InsertResult function
cout<<"*INSERT RESULT SUCCESSFULLY!"<<endl;
else
cout<<"*INSERT RESULT FAILED!"<<endl;
system("pause");
break;
}
case 5:
{
system("cls");
/*if(InsertSubject("subject.txt",&list)) //Call InsertSubject function
cout<<"*INSERT SUBJECT SUCCESSFULLY!"<<endl;
else
cout<<"*INSERT SUBJECT FAILED!"<<endl;*/
system("pause");
break;
}
case 6:
{
system("cls");
cout<<"\nWhere Do You Want To Display The Information?"<<endl;
cout<<"\n1.Screen."<<endl;
cout<<"\n2.File."<<endl;
cout<<endl;
cin>>source;
//check the input
while(!isdigit(source)||source<1||source>2)
{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}
cout<<"\nWhich Information Do You Want To Display?"<<endl;
cout<<"\n1.Student Information."<<endl;
cout<<"\n2.Student Information & Past Exam Result."<<endl;
cout<<"\n3.Student Information & Current Subject Taken."<<endl;
cout<<"\n4.Student Information & Past Exam Result & Current Subject Taken."<<endl;
cout<<endl;
cin>>choice;
//check the input
if(!isdigit(choice) || choice<1 || choice>2)
{
cout<<"\nPlease Enter A Valid Number Of Choice!"<<endl;
cin>>choice;
cout<<endl;
}
Display(&list,choice,source);
system("pause");
break;
}
case 7:
{
system("cls");
cout << "\nThank You For Using The Program!\n";
system("pause");
return 0;
}
}
}
cout << endl;
system("pause");
}

isdigit expects you to pass a character variable to it. The link I provided has an example:
/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char str[]="1776ad";
int year;
if (isdigit(str[0]))
{
year = atoi (str);
printf ("The year that followed %d was %d.\n",year,year+1);
}
return 0;
}
You don't need to use isdigit because you are already using a int variable. Thus, this is the code you need:
case 6:
{
system("cls");
cout<<"\nWhere Do You Want To Display The Information?"<<endl;
cout<<"\n1.Screen."<<endl;
cout<<"\n2.File."<<endl;
cout<<endl;
cin>>source;
//check the input
while (source < 1 || source > 2)
{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}
}

cant larger than 2
source > 2
and smaller than 1
guessing you mean "can't be smaller than 1" source < 1
demo:
#include <iostream>
#include <ctype.h>
using namespace std;
int main(){
char source; // assuming source is char!!
cin>>source;
while(source < '1' || source > '2' || (!isdigit(source)) )
{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}
return 0;
}

Consider changing the code like this
while(!isdigit(source) || source < '1' || source > '2'))
{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}

Try this do-while loop Conditions,
do{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}while(source<1 || source>2 || !isdigit(source));
Edited
char digit; // holds only one char or one digit (0 1 2 3 ...9)
int source;
cin>>digit;
source=digit-'0'; // char to int
do{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}while(source<1 || source>2 || !isdigit(digit));//digit is character
In isdigit(arg) function,pass char argument its working fine.

Related

for loop not running in C plus plus program, without showing any error - CLOSED

It is a very simple program and I have just started learning c++ but the for loop is not working in this program. can anyone tell me why the for loop in this c++ program is not running?
#include <iostream>
#include <string>
using namespace std;
class PrimeNo
{
int a;
int c;
public:
// function to check prime number
void chk_Prime(void)
{
cout << "Enter the number: " << endl;
cin >> a;
c=a/2; // to store the condition
for (int i = 2; i < c; ++i)
{
if (a == 0 || a == 1)
{
cout << "The number is not a prime number" << endl;
break;
}
else if (a % i == 0)
{
cout << "This number is not a prime number" << endl;
break;
}
else //if upper conditions are false a number is a prime number
{
cout << "This number is a prime number" << endl;
break;
}
}
}
};
int main()
{
PrimeNo Num;
Num.chk_Prime();
return 0;
}

Complementary DNA(C++)

Task:Write a code to the new string of Dna According to its pattern. Just so you know In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G".
Fore example:DNA_strand ("ATTGC") //returns "TAACG" or DNA_strand ("GTAT") //returns "CATA"
My Code=>
#include <string>
#include <vector>
#include <iostream>
std::string DNAStrand(const std::string& dna)
{
std::string Sym;
std::string c;
std::stringstream s;
s << Sym;
s >> c;
for(int i = 0; i < dna.size() - 1; i++) {
switch (dna[i]) {
case ('A'):
Sym[i] = 'T';
break;
case ('T'):
Sym[i] = 'A';
break;
case ('C'):
Sym[i] = 'G';
break;
case ('G'):
Sym[i] = 'C';
break;
default:
std::cout << "invalid";
} return c.str();
}
int main() {
std::cout << DNAStrand("ATTGC") << "\n"; //retun "TAACG"
std::cout << DNAStrand("GTAT") << "\n"; //retun "CATA"
}
}
You have created a vector<string>, but in the if statements, you are setting the elements of the vector to chars. You want to build a string, not a vector<string>.
You should replace subsequent if statements with else if, or use a switch statement. Otherwise if statements subsequent to a satisfied if statement are executed needlessly.
Replace this vector with an ostringstream. Naming the stream as s, you would append a char named c with s << c. At the end of iterating over dna, return s.str().

My functions for a vector don't seem to be working? C++ (adding or deleting an item, displaying a vector)

I'm doing an exercise from my textbook that has me create a program that allows the user to manage a list of favorite games by adding, deleting, or viewing the items in the vector. I made use of functions; my program runs, but the functions don't seem to be doing what they're supposed to. I'm able to input a game name for addGame(), but when I input 4 in the do/while loop, no vector is printed. Likewise, the removeGame() function doesn't seem to be working since it displays no message if I type in a game not in the list.
Which function is at fault for the lack of display? Both or just one (addGame or dispGames)? And why is my removeGame function not working?
Thanks for helping.
// exercises ch 4.cpp : main project file.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<iterator>
using namespace std;
void addGame(vector<string> faveGames);
void removeGame(vector<string> faveGames);
void dispGames(vector<string> faveGames);
int main(array<System::String ^> ^args)
{
vector<string> faveGames;
int choice;
cout << "Welcome to the Favorite Games List program!\n\n";
do
{
cout << "What would you like to do?\n\n";
cout << "1 - End program. \n 2 - Add new game to list. \n 3 - Remove game from list. \n 4 - Display list. \n";
cout << "Enter the corresponding number of your choice: ";
cin >> choice;
switch (choice)
{
case 1: cout << "Ending program.\n"; break;
case 2: addGame(faveGames) ; break;
case 3: removeGame(faveGames); break;
case 4: dispGames(faveGames); break;
default: "That is not a valid response, please try again.";
}
}
while(choice != 1);
return 0;
}
void addGame(vector<string> faveGames) {
string newFaveGame;
cout << "Enter the name of the game you want to add: ";
cin >> newFaveGame;
faveGames.push_back(newFaveGame);
}
void removeGame(vector<string> faveGames) {
vector<string>::iterator deletedGameIter;
string deletedGame;
cout << "Enter the name of the game you want to delete: ";
cin >> deletedGame;
for(deletedGameIter = faveGames.begin(); deletedGameIter != faveGames.end(); ++deletedGameIter) {
if(deletedGame == *deletedGameIter) {
faveGames.erase(deletedGameIter);
}
else
{
cout << "That game is not on your list.\n";
}
}
}
void dispGames(vector<string> faveGames) {
vector<string>::iterator iter;
for(iter = faveGames.begin(); iter != faveGames.end(); ++iter)
{
cout << *iter << endl;
}
}
Main problem:
You are passing faveGames by value. Any changes to faveGames don't change the variable in main.
You need to pass them by reference if you want the changes to be visible in main:
void addGame(vector<string>& faveGames);
void removeGame(vector<string>& faveGames);
There are other problems in your code that need to be cleaned up too.
Problem
You have
int main(array<System::String ^> ^args)
This is not standard C++ code. Are you using Microsoft Managed C++?
Problem
You have
faveGames.erase(deletedGameIter);
in removeGame. At that point, deletedGameIter is an invalid object. Incrementing it will lead to undefined behavior. You can change the for loop in that function to:
for(deletedGameIter = faveGames.begin();
deletedGameIter != faveGames.end();
++deletedGameIter) {
if(deletedGame == *deletedGameIter) {
faveGames.erase(deletedGameIter);
return
}
}
if you don't expect to see the game multiple times in the your list. If you expect to see it multiple times, you can use:
for(deletedGameIter = faveGames.begin();
deletedGameIter != faveGames.end(); ) {
if(deletedGame == *deletedGameIter) {
deletedGameIter = faveGames.erase(deletedGameIter);
}
else {
++deletedGameIter;
}
}

String permutation on linking trailing character

I'm writing a game for some highschool kids to learn about computer science/math in general.
But I'm also stuck in a question I've designed for myself, and want to see if there's a more efficient way to solve it.
The question:
Give a word "Abc" and a list of words ["Cat", "Tick", "Apple", "Orange", ... ]
Is it possible to construct a word chain in this condition where last character of the first word is same as the first character of any word chosen from the word list. And can this chain be successfully constructed by the given word list? Return true if possible, false otherwise.
INPUT: boolean lastCharPermutation(String startingWord, String [] wordsList) { .. }
OUTPUT: true for able to complete the combination, false otherwise
For example,
Case #1:
Take "Abc", ["Girl", "King", "Cat", "Dog", "Good", "Tick"]
Return true because Abc-Cat-Tick-King-Good-Dog-Girl
Case #2:
Take "Abc", ["Tour", "Game", "Cat", "Bridge", "Women", "Man"]
Return false because Abc-Cat-Tour and stops there
What you want to do is a Eulerian Path..
I had solved the same problem on Codechef.
This is my Code if you wanna use..
Plz tell me if you need a explanation,it is very easy to understand though.
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
int visit[26];
int adj[26][26];
int count=0;
void scc(int i) //Strongly COnnected Component
{
visit[i]=-1;//visiting
for(int t=0;t<26;t++)
{
if(adj[i][t]>0 && visit[t]==0)//not visited yet
scc(t);
}
visit[i]=1;
count++;
}
int main()
{
string in;
int t,n,k,nv,counta,countb,flag;
int a[26],b[26];
cin >> t;
while(t--)
{
cin >> n;
memset(a,0,26*sizeof(int));
memset(b,0,26*sizeof(int));
memset(visit,0,26*sizeof(int));
memset(adj,0,26*26*sizeof(int));
k=26;count=0;counta=0;countb=0;flag=0;nv=0;
while(n > 0)
{
n--;
cin >> in;
a[in[0]-'a']++;
b[in[in.size()-1]-'a']++;
adj[in[0]-'a'][in[in.size()-1]-'a'] = 1;
adj[in[in.size()-1]-'a'][in[0]-'a'] = 1;
}
for(int i=0;i<26;i++)
if(a[i]>0)
{
scc(i);
break;
}
for(int i=0;i<26;i++)
if(a[i]!=0 || b[i]!=0)
nv++;
if(count!=nv)
flag=1;
while(k > 0 && flag!=1 )
{
if(a[k-1]-b[k-1] == 1)
counta++;
else if(b[k-1]-a[k-1] == 1)
countb++;
else if(a[k-1]!=b[k-1])
flag = 1;
k--;
}
if(flag==0 && counta==countb && ( counta==1 || counta ==0))
cout << "Ordering is possible." <<endl;
else
cout << "The door cannot be opened." <<endl;
}
return 0;
}

logic error in prime # program. The program just ends after I answer the prompt so I can't see the numbers

//Purpose: Display first 'n' (user chosen) number if emirps to the console, five per line.
//Note: An "emirp" is a prime number that is also prime when reversed.
#include <iostream>
using namespace std;
bool isPrime(int value); //Prototyle for "prime number function"
int reverse (int value2); //Prototype for "emirp function"
int main()
{
//Ask the user for a positive number
cout << "Please enter a positive number: ";
int n;
cin >> n;
//Reject negative value input
if ( n < 1)
{
cout << "INVALID NUMBER \n";
}
else
{
//Calculate all emirps up to 'n'.
int test = 0;
int number = 2;
while (test < n)
{
if (isPrime(number) && reverse(number))
{
cout << "\n" << reverse(number) << "\t\t\t";
test++;
}
else
{
test++;
}
}
}
system("pause");
return 0;
}
bool isPrime(int value)
{
//If value is prime, the remainder (count) will be zero twice--for 1 and itself.
int divisor = 1;
int count = 0;
int prime = 0;
if (value % divisor == 0)
{
count++;
++divisor;
}
if (count = 2)
{
return true;
}
else
{
return false;
}
}
int reverse(int value2)
{
//reverse the number
value2*=10;
value2 = value2 %10;
value2/=10;
//same procedure as prime function
int divisor2 = 1;
int count2 = 0;
int emirp = 0;
if (value2 % divisor2 == 0)
{
count2++;
++divisor2;
}
if (count2 = 2)
{
int emirp = value2;
}
return emirp;
}
How does this even build?
if (count = 2)
{
...
}
Also:
your reverse function just returns an int, what do you expect
if (isPrime(number) && reverse(number)) to do with that result?
It's not a good way of working to do the whole calculation again btw:
cout << "\n" << reverse(number) << "\t\t\t"; //you already did this in your "check"
Edit:
And no wonder it doesn't work.
You check the number-value (2) every time, not n
If it is just about viewing the console output :
Press CTRL+F5 to run application in Visual studio.
just provide a getch()in main() function
And your code syntax is not in a right way :
if (count = 2) //count ==2
{
return true;
}
if (isPrime(number) && reverse(number))
{
cout << "\n" << reverse(number) << "\t\t\t";
test++;
}
will call reverse() 2 times.
modify it something like ;
int RevNum = reverse(number);
if (isPrime(number) &&RevNum)
{
cout << "\n" << RevNum << "\t\t\t";
test++;
}

Resources