I want to create a while loop that will allow me to input a mix of string numbers until I input string that contains all characters.
Also, I have a problem with output
int main() {
string name;
string temp;
cout << "Enter your name:";
cin >> name;
cout << endl;
for(auto a:name) {
if(isalpha(a)) {
temp=name;
} else {
while(!isalpha(a)) {
cout << "Enter your name without digit:";
cin >> name;
cout << endl;
}
}
}
cout << temp << endl;
}
for(auto a:name) {
This is a loop over the characters in name, as entered after the prompt "Enter your name:". The current character is assigned to a.
if(isalpha(a)) {
temp=name;
}
If the letter is alphabetic, assign temp = name (every time the current letter is alphabetic... this is not what you want!).
else {
...if the current character (a) is not alphabetic...
while(!isalpha(a)) {
...enter a second loop, which will loop until a is alphabetic...
cout << "Enter your name without digit:";
cin >> name;
cout << endl;
}
...but a is never again assigned to. Your loop does not terminate.
You should re-work your logic. As this looks like a self-study project, I will not write the reworked loop for you, as I think you will learn much more from trying to do it on your own.
Related
I currently try to set up communication between a Windows program and a µC.
I'll show you the code to initialize the port:
int serialCommunication::serialInit(void){
//non overlapped communication
hComm = CreateFile( gszPort.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
0,
0);
if (hComm == INVALID_HANDLE_VALUE){
cout << "Error opening port." << endl;
return 0;
}
else{
cout << "Opened Port successfully." << endl;
}
if (SetCommMask(hComm, EV_RXCHAR) == FALSE){
cout << "Error setting communications mask." << endl;
return 0;
}
else{
SetCommMask(hComm, EV_RXCHAR);
cout << "Communications mask set successfully." << endl;
}
if (GetCommState(hComm, &dcbSerialParams) == FALSE){
cout << "Error getting CommState." << endl;
return 0;
}
else{
GetCommState(hComm, &dcbSerialParams);
cout << "CommState retrieved successfully" << endl;
}
dcbSerialParams.BaudRate = CBR_115200; // Setting BaudRate = 115200
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None
if (SetCommState(hComm, &dcbSerialParams) == FALSE){
cout << "Error setting CommState" << endl;
return 0;
}
else{
SetCommState(hComm, &dcbSerialParams);
cout << "CommState set successfully" << endl << endl;
cout << "+---CommState Parameters---+" << endl;
cout << "Baudrate = " << dcbSerialParams.BaudRate << endl;
cout << "ByteSize = " << static_cast<int>(dcbSerialParams.ByteSize) << endl; //static Cast, um int auszugeben und kein char
cout << "StopBits = " << static_cast<int>(dcbSerialParams.StopBits) << endl; //static Cast, um int auszugeben und kein char
cout << "Parity = " << static_cast<int>(dcbSerialParams.Parity) << endl; //static Cast, um int auszugeben und kein char
cout << "+--------------------------+" << endl;
}
/*------------------------------------ Setting Timeouts --------------------------------------------------*/
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (SetCommTimeouts(hComm, &timeouts) == FALSE){
cout << "Error setting timeouts" << endl;
return 0;
}
else{
SetCommTimeouts(hComm, &timeouts);
cout << "Timeouts set successfully." << endl;
cout << "+--------------------------+" << endl;
return 1;
}
My Read function looks like this:
void serialCommunication::serialRead(void){
bool readStatus;
bool purgeStatus = 0;
bool correctData = 0;
cout << "Waiting for Data..." << endl; // Programm waits and blocks Port (like Polling)
readStatus = WaitCommEvent(hComm, &dwEventMask, 0);
if (readStatus == FALSE){
cout << "Error in setting WaitCommEvent." << endl;
}
else{
cout << "Data received." << endl;
do{
readStatus = ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, 0);
SerialBuffer += TempChar; // add tempchar to the string
}while (NoBytesRead > 0);
SerialBuffer.pop_back(); // Delete last sign in buffer, otherwise one "0" too much shows up, for example "23900" instead of "2390"
cout << endl << SerialBuffer << endl;
SerialBuffer = ""; // Reset string
}
So at some point, my µC sends the String "Init complete...!\r\n" after initializing some things. This works well.Init complete proof
Now after that, the communcation produces errors. I am getting Data I should not receive. The µC can only send data, if a specific string is sent to it by the PC. While debugging I could detect, that the µC never receives this specific string and therefore never sends data. In the following picture, I show you what gibberish I am receiving constantly though.
Receiving Gibberish
/EDIT: I am constantly receiving the same gibberish
The funny thing is, I even receive that data, when the µC is completely switched off (Serial Cables are still connected). So there has to be some data at the port, which just is not deleted. I tried to restart the PC aswell, but it didn't help either.
I will also show you my while loop on PC:
while (testAbbruch != 1){
pointer = acMessung(anzahlMessungen, average); // measurement with external multimeter
cout << endl;
cout << "Average: " << average << endl << endl;
if (average >= 30){
testAbbruch = 1; // there won't be a next while iteration
befehl = "stopCalibration\r\n";
serialTest.serialWrite(befehl);
serialTest.serialRead();
}
else{
cout << "Aktion: ";
std::getline (cin, befehl);
befehl = "increment"; //for debugging
if (befehl == "increment"){
befehl.append("\r\n"); // adding it, so the µC can detect the string correctly
serialTest.serialWrite(befehl);
serialTest.serialRead(); // µC has to answer
}
else if(befehl == "decrement"){
befehl.append("\r\n"); // adding it, so the µC can detect the string correctly
serialTest.serialWrite(befehl);
serialTest.serialRead(); // µC has to answer
}
befehl = ""; // string leeren für nächsten Aufruf
}
}
I know my program is far from perfect, but if I understood the serial Communication with Windows correctly, the buffer is deleted while reading.
Is there any clue you could give me?
EDIT// I just wrote a program that expects one of two inputs: One input is called "increment" the other one is called "decrement". Those inputs are sent to the µC via the serial communication port. Every time I try to send "increment" and instantly after that I am reading from the port, I receive the weird data from this picture. Now, every time I try to send "decrement" and instantly after that I am reading from the port, I receive the weird data from that picture.
//
So my guess is that the data somehow is changed and then looped back to the PC? But why and how?!
(I don't have much english vocabulary, so sry for this weird try of english)
Hi guys! I'm new at C++ and I need to know how to create a filter code that help me at only accept int-eger numbers. I need that this code use only the 'iostream' library. This is because my teacher don't let us use another kind of library (we are new at C++ coding).
Here I put an example of what I have at this moment:
# include <iostream>
# include <limits> //I should't use this library
using namespace std;
int main() {
int value = 0;
cout << "Enter an integer value: ";
while(!(cin >> value)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl <<"Value must be an integer"<< endl << endl; //This line needs <limits>
cout << "Enter another integer value: " ;
}
}
But this code have some inconvenients:
I'm using "#include 'limits'" library and I shouldn't use it
If you enter "1asd" it takes the "1" value, give it like if its correct and it isn't true
Do you guys have any solution for this situation? Thanks in advance for your time.
You just have to check if the bytes that the user entered are numerals like below. If all the bytes of the entered string are numerals (ie between characters 0 and 9), then the entire string is an integer. Except first byte of the string can be a '+', '-', a space/tab or just the first numeral in the number. (Thanks Zett42).
std::cout << "Enter an integer value: ";
std::string res1;
std::cin >> res1;
std::string::iterator it;
for ( it = res1.begin() ; it < res1.end(); it++)
{ std::cout << "checking " << *it << ' ';
if (!( '0' <= *it && *it <= '9' )) {
std::cout << "this is a numeral\n";
} else {
std::cout << "you entered: " << *it << " -- this is *not* a numeral\n";
}
}
my assignment asks me to open a file, but if it doesn't open you are given 3 tries, but when I input the correct file on my second and third try it still give me the error I wrote 'ERROR: File " << input_filename << " could not be opened for input"' and goes to my else statement
char input_filename[90];
ifstream input;
cout << "Type the name of the input file which will hold the simulation results : " << endl;
cin>> input_filename;
input.open(input_filename);
if (input.fail())//if the file doesn't open it will go to the do while loop error message
{
int i = 0;
int h = 0;
do
{
cout << "ERROR: File " << input_filename << " could not be opened for input" << endl;
cin >> input_filename;// allows user to reinput filename
input.open(input_filename);//opens file
if ( !input.fail())
{
cout << "if statement" << endl;
h++;// if h doesn't equal 1 it goes out of the loop
}
else
{
cout << "else statement" << endl;
i++;//post-decrement allows for 2 more tries to input file
}
if (i >= 2)
{
cout << "ERROR: You exceeded maximum number of tries allowed" << endl;
cout << "while entering the input file name" << endl;
return 1;// return 1 represents the error of the input not opening after the 3rd time of inputing
}
} while (i < 2 && h != 0);// do while because it need to be a post condition for two varibles
}
If you reach line 106, it implies your file input succeeded. At that line you should NOT increment h. In fact you should leave h at zero if you want to break out of the loop (Assuming the file input worked).
For a class declaration as below:
class A{
public:
A(int);
~A()
private:
int a;
};
And a constructor definition as follows:
A::A(int i){
a = i;
cout << a << endl;
}
I would like to do something like this from main():
int main(){
int i;
//user input for value
//stored inside i
cout << "The value is " << A obj(i);
return 0;
}
I now get the following error for the above code in main():
error: 'A' does not refer to a value
What is the cause of this error?
You cannot declare obj and output it on the same line. If you want obj to remain available after printing, do this:
A obj(i);
cout << "The value is " << obj;
Otherwise, skip obj in favor of a temporary object:
cout << "The value is " << A(i);
You cannot have a declaration in the middle of another line.
What you can do is create an A on the fly with casting (A) i, or simply A(i), this will cast the int i into an A, and then send it to cout. The temporary A object is then directly discarded.
If you want to keep it, you have to declare a name for it, in its own statement.
You need to first output the message "The value is " on first code line. On the second code line you create the object obj of type A which will output the i.
int main()
{
int i;
cout << "The value is ";
A obj(i);
return 0;
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm a beginner in C++ (4 days or so into my course) i created a small program that seems to work the way i want it to.
Quick summary:
The program asks for your name.
then asks for two numbers to add together.
displays the answer.
then asks if you want to calculate again y/n.
However, i can't help but feel like its a total train wreck in terms of formatting.
In particular the Again() function...
Inside of it, i created a loop by calling on another function if the condition was true. like so:
bool Again() {
std::cout << "Would you like to calculate again y/n?\n";
std::string answer = "";
std::cin >> answer;
if (answer[0] == 'y') {
std::cout << "Cool lets do it then \n";
PickTwo();
Again();
}
else {
std::cout << "alright, goodbye\n";
}
return 0;
}
Is it proper or improper to create a loop the way i did in Again() ?
if so, is there a right way to do it ?
This is the entire program:
#include <iostream>
#include <string>
void Greetings();
int PickTwo();
bool Again();
int main() {
Greetings();
PickTwo();
Again();
system("pause");
return 0;
}
void Greetings() {
std::cout << "Hi my name is Program, we're going to do something today. \n";
std::cout << "Whats your name?\n";
std::string Name;
std::getline(std::cin, Name);
std::cout << "Hi " << Name << ", we're going to try to do math\n";
return;
}
int PickTwo() {
std::cout << "Please pick the numbers to be added\n";
int firstNumber;
std::cin >> firstNumber;
int secondNumber;
std::cin >> secondNumber;
int Answer = firstNumber + secondNumber;
std::cout << "This are your numbers " << firstNumber << " and " << secondNumber << std::endl;
std::cout << "If we add them you have " << Answer << std::endl;
return Answer;
}
bool Again() {
std::cout << "Would you like to calculate again y/n?\n";
std::string answer = "";
std::cin >> answer;
if (answer[0] == 'y') {
std::cout << "Cool lets do it then \n";
PickTwo();
Again();
}
else {
std::cout << "alright, goodbye\n";
}
return 0;
}
Thank you in advance, knowing what NOT to do will help me fix the bad habits before they get worst.
Is it proper or improper to create a loop the way i did in Again() ? if so, is there a right way to do it ?
In a language that does not support tail recursion, your program has the potential to cause stack overflow. I would not recommend using it they way you have it coded.
It will be better to use a while loop or a do-while loop. In the loop, do whatever you need to do again.