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;
}
}
Related
I was assigned a homework to input as many letters as the user wants and stop after input q or Q. Then the programs should output how many vowels there were in such string. We're supposed to use _getche() function but I have MacBook so it doesn't work.
I've tried making conio.h.
I've tried also using cin.get() and getchar() but none work.
__getche() is not a standard function and conio.h is not a standard header. The usual way of doing this is:
int main() {
int ch;
int vowel_count = 0;
while ((ch = getchar()) != 'q' && ch != 'Q' && ch != EOF) {
vowl_count += is_vowel(ch);
}
}
#include <iostream> // getchar(), std::cout
#include <cctype> // tolower()
int main()
{
int count = 0;
for (;;) // infinite loop
{
char c = getchar(); // read a single char from stdin
if (tolower(c) == 'q') // if input is 'q' or 'Q'
break; // break out of the loop
// check for vowel here
{
count++;
}
}
std::cout << "You typed in " << count << " vowels!\n";
return 0;
}
i think you need it:
#include <conio.h>
using namespace std;
int main()
{
bool h = true;
while(h){
char ch;
ch = getche();
if(ch=='q' || ch == 'Q'){
h = false;
}
}
return 0;
}
I am trying to read a single character multiple times. The catch is that I need to prevent user errors. So for example:
char arr[10];
for(int i = 0; i < 10; i++)
{
cin.get(arr[i]);
}
Where the inputs should be something like a, b, c, d, .... But if someone were to enter ab for the first entry I want to capture the a and then ignore the b. I know about cin.ignore however I don't know how I would go about ignoring an arbitrary number of alphanumeric characters or symbols considering that I want to ignore a potentially unlimited number of characters and then stop ignoring and read again.
How can I either ignore an arbitrary number of characters and then stop ignoring or how can I actually flush the buffer for cin.
Most input is line feed so if you want to ignore all characters in the input stream until you hit a newline then you could use:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Since we ignore up to the streamsize there should not be an extra content in the input buffer.
If you want user to hit enter after each symbol, then code could be as simple as this:
char arr[10];
for(int i = 0; i < 10; )
{
std::string line;
std::getline( std::cin, line );
// check that line is not empty
if( line.empty() ) {
std::cout << "missing input" << std::endl;
continue;
}
arr[i++] = line[0]; // get only first symbol and ignore the rest
}
if you have something else in mind, I am afraid that will not work with std::cin - you do not see any input until user presses enter. In that case you would have to use OS specific functions to get unbuffered input.
The following is the code that you want, if your inputing like this a 'enter' b 'enter' c 'enter' etc...
#include <iostream>
#include <string>
using namespace std;
int main() {
char arr[10];
string line;
for (int i = 0; i < 10; i++)
{
getline(cin, line);
arr[i] = line[0];
cout << endl << "Here is the Char: " << arr[i] << endl;
}
return 0;
}
BUT if you enter input like this in one line: a,b,c,d,e,f,g,h,i,j 'enter' then you want the following code:
#include <iostream>
#include <string>
using namespace std;
int main() {
char arr[10];
string line;
int i = 0;
size_t end;
getline(cin, line);
end = 0;
int counter = 0;
if (line != "") {
while (end != string::npos && counter < 10) {
if (counter == 0) {
arr[counter] = line[0];
}
else {
end = line.find(",", end + 1);
arr[counter] = line[end + 1];
}
counter++;
}
}
for (int i = 0; i < 10; i++) {
cout << endl << "Here is the Char: " << arr[i] << endl;
}
return 0;
}
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).
This part of a larger project. Right now it's supposed to ask user for a string, calculate how many words are in it, print out the # of words, ask user if they want to do it again, then if they want to, ask for another string, and so on. But this only works fine the first time. After that, it takes the answer to the yes/no question as the test string. For example: I like coding. 3. Again? Yes/no. Yes. 1. Again? Yes/no... Can someone tell me how to fix this glitch?
#include <iostream>
#include <string>
using namespace std;
string original[10] = { "hello", "sir", "madam", "officer", "stranger", "where", "is", "the", "my", "your" };
string translated[10] = { "ahoy", "matey", "proud beauty", "foul blaggart", "scurvy dog", "whar", "be", "th'", "me", "yer" };
string input;
string ans;
bool playAgain()
{
cout << "Another? yes/no: ";
cin >> ans;
if (ans.compare("yes") == 0) { return true; }
if (ans.compare("no") == 0) { return false; }
}
int getNumOfWords(string input)
{
int numOfSpaces = 0;
string current;
for (int i = 0; i < input.length(); i++)
{
current = input.at(i);
if (current.compare(" ") == 0)
{
numOfSpaces++;
}
}
return numOfSpaces + 1;
}
void play(string input)
{
int numOfWords = getNumOfWords(input);
cout << numOfWords << endl;
}
void start()
{
getline(cin, input);
play(input);
}
int main()
{
bool playing;
do
{
start();
playing = playAgain();
} while (playing);
return 0;
}
When cin.getline() reads from the input, there is a newline character left in the input stream, so it doesn't read your c-string. Use cin.ignore() beore calling getline()
void start()
{ cin.ignore();
getline(cin, input);
play(input);
}
It's because of the difference between getline and cout. The former reads in the entire line up to and including the terminating \n, while cout will read only up to the \n or whitespace. The cin in your code reads in yes or no to ans (try printing it out immediately afterwards), but it doesn't account for the \n. Thus, when you call getline it finds the \n waiting in stdin, and so reads that into input instead of blocking until cin wasn't empty.
I am getting into c++ right now, and right now I want to know the most common/best way to catch invalid input. I would love answers to this wide open question, but my more specific question is as follows.
I want a char from the user. If the char is 'y' then it will repeat, if it is 'n' then the program will close. If I enter multiple chars then it will repeat as many times as chars e.g. I enter 'hello' it will show my output 5 times. I assume that it reads each char and goes through the whole loop then reads the next char in line. How can I get it to show up just one time?
bool valid = 0;
while(valid)
{
...
bool secValid = 0;
while(secValid == 0)
{
cout << "To enter another taxable income type 'y': \n\n";
char repeat = NULL;
cin >> repeat;
if(repeat == 'y')
{
valid = 0;
secValid = 0;
system("cls");
}else if(repeat == 'n')
{
return;
}else
{
secValid = 1;
}
}
}
You could structure it something like this:
while(true) {
cout << "Repeat (y/n)? ";
string line;
if(!getline(cin, line))
break; // stream closed or other read error
if(line == "y") {
continue;
} else if(line == "n") {
break;
} else {
cout << "Invalid input." << endl;
}
}
Example session:
Repeat (y/n)? y
Repeat (y/n)? foo
Invalid input.
Repeat (y/n)? n
Here we use std::getline to get a whole line of input, instead of getting one character at a time.
std::getline():
std::string line;
std::getline(std::cin, line);
if (line == "y") {
// handle yes
}
else if (line == "n") {
// handle no
}
else {
// handle invalid input
}
use std::getline from the <string> header to read a line of input into a std::string
Also when checking string for "y" or "n" is good practise to use upcased string instead. For example
std::string YES = "Y";
std::string NO = "N";
...
std::string line;
std::getline(std::cin, line);
std::transform(line.begin(), line.end(), line.begin(), std::toupper);
if (line == YES)
{
...
}
else if (line == NO)
{
..
.
}