The task is to cin>>...., take only letters, change upper case letters to lower case and rewrite line with only lower case letters. I cannot figure out why my code is ignoring the first letter entered.
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char ch;
cin >> ch;
while (ch != '#'){
if (cin.get(ch))
{
if (isalpha(ch)){
if (isupper(ch)){
cout <<(char)tolower(ch);
}
else
cout << ch;
}
if (ch == '\n')
cout << "\nNie zakonczyles ciagu znakiem #" << endl;
}
else{
cin.clear();
}
}
}
Because the loop uses cin.get(ch) to get the character to print, but the first character is actually read with cin >> ch; and then the result is discarded.
You might want to get rid of the cin>>ch; instruction and initialize ch to a value different from '#', or transform the loop into a do-while loop, similar to this:
char ch;
do
{
if (cin.get(ch))
{
/* Do what is needed */
}
}
while (ch != '#')
cin >> ch; <- read first letter
while (ch != '#'){
if (cin.get(ch)) <- read next letter which tosses out the first letter
To fix this set ch to some value and then get rid of cin >> ch;
Because just after cin >> ch; you're doing cin.get(ch).
Related
In my program, I am trying to check the user's input. I want him to press a given character. But my code doesn't ignore pressing CTRL+D, it becomes an infinite loop.
char ch;
cin >> ch;
while(ch != 'c' && ch != 'C'){
if (cin.eof()){
cin.clear();
}
cin >> ch;
}
Is there a way to fix this?
When I do this:
char ch;
cin >> ch;
while(ch != 'c' && ch != 'C'){
if (cin.eof()){
std::clearerr(stdin);
}
if (cin.eof()){
std::clearerr(stdin);
}
cin >> ch;
}
The second if is still true.
I am trying to do something like Press any key. I can"t seem to figure it out.
I'm looking for a way to break a for loop using enter in the visual studio console.
do {
std::cin >> userInput;
if (userInput == '\n')
break;
lineStorage[lineLength] = userInput;
lineLength++;
} while(true);
This is what I have so far, but the newline character won't work for what I need it to. Any suggestions or insight would help.
P.S. I cannot use a sentinel value other than the newline character resulting from the enter button.
P.S. More context:
char lineStorage[80] = { 'a' };
char userInput = ' ';
const char lineEnd = '\n';
int lineLength = 0;
std::cout << "Enter a line:";
do {
std::cin >> userInput;
if (userInput == '\n')
break;
lineStorage[lineLength] = userInput;
lineLength++;
} while (true);
Reading with >> by default skips whitespace, and a newline is whitespace. I suggest using getline() instead:
for(int i = 0; i < 80; i++) {
if (!getline(std::cin, userInput) || userInput.empty())
break;
lineStorage[lineLength] = userInput;
lineLength++;
}
If your lineStorage is really supposed to store individual words, you can split userInput on spaces before storing the words.
Edit: now that you've shown that userInput is a single character, I think you should just use std::cin.get(userInput) to read one character at a time. That will let you get the newlines in the style of your original code.
I like the other answer better, but something like this should also work:
do {
cin.get(userInput);
if (userInput == 10) {
break;
} else {
lineStorage[lineLength] = userInput;
lineLength++;
}
} while (true);
more clear will be
#include <stdio.h>
#include <stddef.h>
int main(int argc , char *argv[])
{
char t[70]={0},x;
while(1)
{
scanf("%[^ ^\n]%c",t ,&x);
if(x == '\n') break;
}
}
"Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them.
Exit the program when a terminating '|' is entered."
my attempt
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int firstnumber;
int secondnumber;
int stopnumber;
while(stopnumber!='|'){
cout <<"Please enter an integer, followed by another integer: \n";
cin >> firstnumber >> secondnumber;
cout <<"\n" << firstnumber <<" "<< secondnumber<< " \n";
}
return 0;
}
the program takes 2 number and prints them, but when i enter '|' , it goes in infinite loop. How to stop the program when i enter '|'
Thanks
This is how your loop should look like:
Read a character (std::cin::get).
If successful and your character is the stop symbol, break the loop.
If your character is not a digit (::isdigit), continue looping.
If your character is a digit, put it back(std::cin::putback).
Read two integers.
If successful, display them, if not, clear the stream (std::cin::clear).
You will have to patiently try to understand what get, putback & isdigit are doing.
[EDIT]
Run it
#include <iostream>
#include <cctype>
int main()
{
char c;
while ( std::cin.get( c ) && c != '|' )
{
if ( !std::isdigit( c ) )
continue;
std::cin.putback( c );
int i, j;
if ( std::cin >> i >> j )
std::cout << i << ' ' << j << std::endl;
else
std::cin.clear();
}
return 0;
}
Your loop is testing stopnumber which is never set. If you set stopnumber to either firstnumber or secondnumber then perhaps you can get your logic to work but there is a step missing as it is.
Ok, I think I have found my answer
I tried putting my cin in the while loop as such
int firstnumber;
int secondnumber;
while (cin >> firstnumber >> secondnumber)
And it worked! Thanks everyone for your help
This depends on whether you need to exit directly after you receive the '|' character or whether you mind running through the rest of the loop first before exiting it......
Personally I'd want to exit straight after receiving the '|' so would follow the basic idea of....
int a,b;
while(){
read your values a,b in
if (a='|' || b='|'){exit()};
print your values
}
std::stoi(std::string) - returns int from std::string
#include <iostream>
#include <string>
bool isNumber(std::string &str) {
for (auto i : str) {
if (i < '0' || i > '9') return false;
return true;
}
int main () {
int a, b;
std::string s;
while (true) {
std::cin >> s;
if (s == "|" || !isNumber(s)) break;
a = std::stoi(s);
std::cin >> s;
if (s == "|" || !isNumber(s)) break;
b = std::stoi(s);
std::cout << a << " " << b << std::endl;
}
return 0;
}
I'm making a small desk cost program for a class. I wanted to include a loop into it. But every time I get to the end of the program and loop it back to the beginning, it skips the part where I ask for the customers name and leaves it blank. Any idea how to fix it?
Here's my code:
#include <iostream> // needed for Cin and Cout
#include <string> // needed for the String class
#include <math.h> // math functions
#include <stdlib.h>
using namespace std;
#define baseCost 200.00
#define drawerPrice 30.00
int main(void)
{
while(true)
{
string cname;
char ch;
cout << "What is your name?\n";
getline(cin, cname);
cout << cname;
cout << "\nWould you like to do another? (y/n)\n";
cin >> ch;
if (ch == 'y' || ch == 'Y')
continue;
else
exit(1);
}
return 0;
}
The problem is that you need to call cin.ignore() after your prompt for exit. When you use cin to get the 'ch' variable, a newline character is still stored in the input buffer. Call cin.ignore(), to ignore that character.
If you don't, you'll notice that the program prints a newline as the name on the second loop.
You could also make the 'ch' variable a string like 'cname' and use getline instead of cin. Then you wouldn't have to issue the cin.ignore() call.
#include <iostream> // needed for Cin and Cout
#include <string> // needed for the String class
#include <math.h> // math functions
#include <stdlib.h>
using namespace std;
#define baseCost 200.00
#define drawerPrice 30.00
int main()
{
while(true)
{
string cname;
char ch;
cout << "What is your name?\n";
getline(cin, cname);
cout << cname;
cout << "\nWould you like to do another? (y/n)\n";
cin >> ch;
// Slightly cleaner
if (ch != 'y' && ch != 'Y')
exit(1);
cin.ignore();
/*
if (ch == 'y' || ch == 'Y')
continue;
else
exit(1);
*/
}
return 0;
}
I tried to write a code that asked me to input numbers one by one and when a certain char was inserted ( in this case 'x' ) it would stop the loop. But when I insert that char it starts spamming me with "Insert Number" . I think that the fault is that I'm trying to insert a char in an int array, but I can't think a way around it.
long int numbers[100]={0};
char h='y';
int index=0;
do
{
cout << "Insert Number : ";
cin >> numbers[index];
h=(char)numbers[index];
index++;
}
while(h!='x');
This happens because 'x' is not a number and cin >> numbers[index]; operation fails, without consuming that data. So the loop continues, gets the same x, fails again and everything starts all over again. You can check for result of input operation, something like this:
#include <iostream>
using namespace std;
int main ()
{
long int numbers[100]={0};
char h='y';
int index=0;
do
{
cout << "Insert Number : ";
if (cin >> numbers[index])
{
h=(char)numbers[index];
index++;
}
else
{
cout << "Hey, that was not a number! Bye." << endl;
break;
}
}
while(h!='x');
}
You should write a loop as:
while(cin >> numbers[index])
index++;
It will read all the integers, untill you enter some invalid input, be it 'x' or any other character. Now if you want to skip all invalid inputs and continue reading integers (which might be after invalid inputs), and want to consider only 'x' to exit from the loop, then wrap the above loop with another loop as:
char ch;
do
{
while(cin >> numbers[index])
index++;
cin.clear(); //clear the error flags, so you can use cin to continue reading
cin >> ch; //read the invalid character
} while(ch != 'x');
One piece of advice: prefer using std::vector<long int> over long int numbers[100]. What if user entered more than 100 integers, then your program will be corrupted.
Because you're trying to read in an integer, any character that isn't a digit can't be converted to a number and will jam up the input - you'll get an error and the bad character will not be removed from the stream. The next time you try to read you'll get the same error.
If you expect a number or a string, always read the input as a string, and try converting it to a number afterwards if the string isn't "x":
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main(int argc, char *argv[])
{
std::vector<long int> numbers;
std::string line;
while(std::getline(std::cin, line) && line != "x") {
std::istringstream input(line);
long int value;
// Check that there is only a number with nothing else after
if((input >> value) && input.get() == std::char_traits<char>::eof()) {
numbers.push_back(value);
} else {
std::cout << "Invalid Entry, please retry" << std::endl;
}
}
//...
return 0;
}