Issue with making a loop - loops

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
string checkpass(string password1)
{
string rightpass = "aimen";
string errormsg2;
if (password1 == rightpass)
{
errormsg2 = "Right";
}
else{errormsg2 = "No";}
return errormsg2;
}
int main()
{
string password;
string errormsg;
cout << "Type the password";
loop:
getline (cin,password);
errormsg == checkpass(password);
if (errormsg=="Right")
{
cout << "Admitted" << endl;
}
else {
goto loop;
}
system("pause");
return 0;
}
Console doesn't print the word "Admitted". It launches, but after my putting in the console words, repeatedly occur nothing.
I request your aid. Thank you.

You are comparing with errormsg == checkpass(password); when you should assign with one = symbol.

Related

LLVM Pass to insert an external function call to LLVM bitcode

I am writing an LLVM pass to instrument a C source program. I want to insert a function call before each branch instruction which calls an external function like this :
void print(int x){
printf("x = %d\n", x);
return;
}
I want to link this external function to C source code using llvm-link tool and then instrument the code using opt tool.
Ths pass that I have implemented is like this:
#include "llvm/Pass.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/IRBuilder.h"
#include <vector>
using namespace llvm;
namespace{
struct ir_instrumentation : public ModulePass{
static char ID;
Function *monitor;
ir_instrumentation() : ModulePass(ID) {}
virtual bool runOnModule(Module &M)
{
std::vector<Type *> args;
args.push_back(Type::getInt32Ty(M.getContext()));
ArrayRef<Type*> argsRef(args);
FunctionType *FT = FunctionType::get(Type::getVoidTy(M.getContext()), args, false);
Constant* myFunc = M.getOrInsertFunction("print", FT, NULL);
minitor = cast<Function>(myFunc);
for(Module::iterator F = M.begin(), E = M.end(); F!= E; ++F)
{
for(Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
{
for(BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI)
{
if(isa<BranchInst>(&(*BI)) )
{
errs() << "found a branch instruction!\n";
ArrayRef< Value* > arguments(ConstantInt::get(Type::getInt32Ty(M.getContext()), 5, true));
Instruction *newInst = CallInst::Create(monitor, arguments, "");
BB->getInstList().insert(BI, newInst);
errs() << "Inserted the function!\n";
}
}
}
}
return true;
}
};
char ir_instrumentation::ID = 0;
static RegisterPass<ir_instrumentation> X("ir-instrumentation", "LLVM IR Instrumentation Pass");
}
LLVM is configured and built fine with this pass but when I use opt, I get this error :
opt: /llvm/lib/IR/Type.cpp:281:
llvm::FunctionType::FunctionType(llvm::Type*, llvm::ArrayRefllvm::Type*, bool):
Assertion `isValidReturnType(Result) && "invalid return type for function"' failed.
I think the problem is something like mismatching between the function type that I have declared and the external function (like the context).
LLVM version: LLVM version 7.0.0svn
Until now I have not solved the problem.
Thanks
I could finally solve this problem and successfully instrument LLVM bitcode. After a lot of trouble with function getOrInsertFunction, I found out it is not really necessary to use this method in my case. I just simply changed my pass to this:
#include "llvm/Pass.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/IRBuilder.h"
#include <vector>
using namespace llvm;
namespace{
struct ir_instrumentation : public ModulePass{
static char ID;
Function *monitor;
ir_instrumentation() : ModulePass(ID) {}
virtual bool runOnModule(Module &M)
{
errs() << "====----- Entered Module " << M.getName() << ".\n";
int counter = 0;
for(Module::iterator F = M.begin(), E = M.end(); F!= E; ++F)
{
errs() << "Function name: " << F->getName() << ".\n";
if(F->getName() == "print"){
monitor = cast<Function>(F);
continue;
}
for(Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
{
for(BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI)
{
if(isa<BranchInst>(&(*BI)) )
{
errs() << "found a brach instruction!\n";
ArrayRef< Value* > arguments(ConstantInt::get(Type::getInt32Ty(M.getContext()), counter, true));
counter++;
Instruction *newInst = CallInst::Create(monitor, arguments, "");
BB->getInstList().insert(BI, newInst);
errs() << "Inserted the function!\n";
}
}
}
}
return true;
}
};
char ir_instrumentation::ID = 0;
static RegisterPass<ir_instrumentation> X("ir-instrumentation", "LLVM IR Instrumentation Pass");
}
As I know the name of the external function, I can simply find it through iterating over all functions of module and then use it in the desired way.
Obviously the problem was caused by calling module->getOrInsertFunction and the function type. My experience says that this method is more useful when you want to insert a new function and declare the prototype of your own function. Using it to get an existing function is challenging (e.g. setting the right prototype, ...)
Thanks

I need a proper while condition for my loop

Here i have a while loop which is ment to have a condition to be satisfied, when i receive the whole message from My Arduino. The problem is that: i dont know how i could change this condition
do
{
read_result = arduino.readSerialPort(incomingData, MAX_DATA_LENGTH);
//prints out data
if (read_result > 0)
cout << incomingData;
//puts(incomingData);
} while (true);
i have inspired all my project from Here
but i have changed the main function and my arduino file. here is my main function:
//This code snippet will help you to read and write data from arduino
//#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "SerialClass.h"
#include <fstream>
//using namespace std;
using std::cin;
using std::cout;
using std::endl;
//String for getting the Output from Arduino
char outputData[MAX_DATA_LENGTH];
//String for incoming data
char incomingData[MAX_DATA_LENGTH];
//Portname must contain these backslashes
char *port_name = "\\\\.\\COM5";
const unsigned int bufSize =255;
int main()
{
SerialPort arduino(port_name);
if (arduino.isConnected())
std::cout << "Connection Established! \n" << std::endl;
else
std::cout << "ERROR, check port!";
while (arduino.isConnected()) {
std::string input_string ;
//cout << "Write something: \n";
getline(cin, input_string);
//Creating a c string
char *c_string = new char[input_string.size() + 1];
//copying the std::string to c string
std::copy(input_string.begin(), input_string.end(), c_string);
//Adding the delimeter
c_string[input_string.size()] = '\n';
//Writing string to arduino
arduino.writeSerialPort(c_string, MAX_DATA_LENGTH);
//Getting reply from arduino
arduino.readSerialPort(outputData, MAX_DATA_LENGTH);
//printing the output
//puts(outputData);
//freeing c_string memory
delete[] c_string;
//Check if data has been read or not
int read_result;
do
{
read_result = arduino.readSerialPort(incomingData, MAX_DATA_LENGTH);
//prints out data
if (read_result > 0)
cout << incomingData;
//puts(incomingData);
} while (true);
//wait a bit
//Sleep(100000);
}
}
and here is my arduino file:
int PButton=2;
int Led=13;
unsigned long start,finished,elapsed;
void setup() {
Serial.begin(9600); //begins the Serial Connection.
pinMode(PButton, INPUT_PULLUP);
pinMode(Led,OUTPUT);
digitalWrite(Led,LOW);
Serial.println("Is the video already started? ""yes/no""...\n");
start=millis();
String ans;
while(Serial.available()<=0)
{
}
ans=Serial.readStringUntil('\n');
if(ans.equals("yes")){
digitalWrite(13,HIGH);
Serial.println("The video is started!\n\nplease Press the Pushbutton when the task is fullfilled!\n");
}
else if(ans.equals("no")){
digitalWrite(13,LOW);
Serial.println("The Video is still not started! \n");
}
}
void loop() {
int buttonState=digitalRead(PButton); //read the input pin
if(buttonState==LOW)
{
Serial.print("The pushbutton is pressed after ");
finished=millis();
elapsed=finished-start;
Serial.println(elapsed);
delay(3000);
}
}

Why the loop stops before it's end?

#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
string name = get_string();
for(int i=0;i<strlen(name);i++ )
{
//printf("%c\n",name[i]);
if(name[i]=='\0' && name[i+1]!='\0') //try to print the next char of space
{
if(name[i+1]<='z' && name[i+1]>='a')
{
printf("%c",name[i+1]);
}
if(name[i+1]<='Z' && name[i+1]>'A')
{
printf("%c",name[i+1]);
}
}
else;
}
}
get_string() is to get users input as a string.
After I run this, it only print the first char that I input,which means the loop stops.
Is there anything wrong with my conditon lines?
after I change for(int i=0;i<strlen(name);i++ ) to for(int i=0;i<strlen(name)-1;i++ ),it gives me a Segmentation fault. I will look into it more.
Now I know why.
I thought '\0' equals ' ' ,and they are both the end of a string and space,which is very wrong.
All because of my bad english. I learnt it wrong from very begaining.
Stupid question.But I don't want to delete it,since maybe someone like me can use it.
This is my final answer.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
void caps(char x);
int main(void)
{
string name = get_string();
if (name!=NULL){
for(int i=0;i<strlen(name);i++)
{
// printf("%c\n",name[i]);
if(i==0&&name[0]!=0)
{
caps(name[0]);
}
if(name[i]==' '&& name[i+1]!=' ') //try to print the next character
{
caps(name[i+1]);
}
}
}
}
void caps(char x)
{
if(x<='z' && x>='a')
{
printf("%c",x-('a'-'A'));
}
if(x>='A' && x<='Z')
{
printf("%c",x);
}
}

Unable to access a Private Array

I'm having difficulty accessing an array of strings. It is declared as a private array and filled in the constructor for the class. I have a Get function defined. The problem is when I call this function at compile time I get an error that I cannot access private member declared in class. I'm just getting back into coding just for the yuks, as such I'm at a stage pre-pointers and pre-vectors so I'm trying to avoid situations that would force their use.
Words.h
#pragma once
#include <string>
#include <iostream>
#include <array>
class Words {
Words();
public:
std::string GetNewWord(int);
private:
std::string WordList[23] = {};
};
Words.cpp - The Array is completely filled but shortened here
#include "Words.h"
Words::Words(){
WordList[0] = "omega";
WordList[1] = "minors";
WordList[2] = "stigma";
WordList[3] = "glamor";
WordList[4] = "savior";
WordList[5] = "disarm";
WordList[6] = "isogram";
.
.
.
;
}
std::string Words::GetNewWord(int choice)
{
return WordList[choice];
}
main.cpp - contains an infinite loop so i could quickly test if the array was populated
#include <iostream>
#include <string>
#include "Words.h"
Words word;
int main() {
do {
std::cout << "choice: ";
int choice;
std::cin >> choice;
std::cout << "\n" << word.GetNewWord(choice) << "\n";
} while (true);
return 0;
}
The constructor is private, as all members of a class are by default. Simply move it to the public section.

C++ program crashed when loading array of objects

Hello i'm trying to fill an array of objects from a text file in c++ , but i have a crash every time i run the program. I'm i at the right direction here? Is there any more eficient way to do it?
main.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include "Item.h"
using namespace std;
void readItems(FILE *products, Item pList[]);
FILE *products;
int main()
{
Item pList[5];
readItems(products,pList);
return 0;
}
void readItems(FILE *products, Item pList[]){
products = fopen("data.txt", "r");
int i = 0;
fread(&pList[i], sizeof(pList), 1, products);
while (!feof(products))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}
fclose(products);
}
Item.cpp
#include "Item.h"
#include <stdio.h>
#include <string>
#include <conio.h>
#include <iostream>
using namespace std;
Item::Item()
{
code = 0;
description = "";
price = 0;
}
Item::Item(int code1,string description1,float price1)
{
code = code1;
description = description1;
price = price1;
}
void Item::printData(){
cout<<endl<<"Code:"<<code<<"\tName:"<<description<<"\tPrice:"<<price;
}
void Item::setData(int code1,string description1,float price1){
code = code1;
description = description1;
price = price1;
}
int Item::getCode(){
return code;
}
float Item::getPrice(){
return price;
}
Item::~Item()
{
//dtor
}
The new code is like that , but it prints a set of some chars of the txt file with some weird symbols .
void readItems(FILE *fin, Item list[]){
int i=0;
products = fopen("items.txt","r");
fread(&list[i],sizeof(list[i]),1,products);
list[i].printData();
while(!feof(products) && i<5){
fread(&list[i],sizeof(list[i]),1,products);
list[i].printData();
i++;
}
fclose(products);
}
Try replacing
while (!feof(products))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}
with
while (!feof(products) && (i < 5))
{
i++;
fread (&pList[i], sizeof(pList), 1, products);
}

Resources