Detecting if the user enters space or enter in a conditional with cin.get() - c++

I'm trying to get this input loop to stop if the user enters a space ' ' or enter \n but the space part doesn't seem to work, even when I replace in != ' ' with in != 32 which is the ASCII code for space.
#include<iostream>
using namespace std;
int main()
{
int temp, cho = 0;
char in = '0';
while (in != '\n' && in != ' ')
{
in = cin.get();
temp = in - '0';
if (temp >= 0 && temp <= 9)
cho += temp;
}
}
Is it even possible to achieve with cin.get() and a console application?

You actually have three problems here that won't be independently distinguishable from each other to begin with, but which become clear once you apply the reasoning below:
I. Boolean conditional is incorrect
while (in != '\n' || in != ' ')
This is wrong! You probably meant &&.
(A != B || A != C) is always true (assuming B and C are different, as they are in your example) because A cannot possibly equal both of them at the same time.
II. Program logic is in the wrong order
Furthermore, you're checking this in the wrong place. You're doing this:
Set input #0 to '0' to get us going
Does the input #0 meet my exit criteria? (no)
Take input #1
Deal with input #1
Does the input #1 meet my exit criteria? (no)
Take input #2 (say this is a space)
Deal with input #2
Does the input #2 meet my exit criteria? (YES!)
End the loop
You see how you check input #2 too late? It's already been "dealt with". You'll exit the loop just fine after implementing the above fix, but you've already appended the character to cho.
How about this:
int temp, cho = 0;
// Get input for the first iteration
char in = cin.get();
while (in != '\n' && in != ' ')
{
temp = in - '0';
if(temp >=0 && temp <=9)//so only the ASCII of digits would be entered
cho += temp;
// Now get input for the next iteration
in = cin.get();
}
The duplication isn't nice, but you can fiddle with it as you please once the logic's correct.
III. Your terminal has line buffering turned on
Finally, even with this code you may experience problems due to line buffering in your terminal: your program will be functioning absolutely correctly, but since your characters are often by default not sent to the program until a whole line is provided, there is no "live"/"instant" reaction to the act of pressing a space. Only once you hit enter are all those characters finally submitted to your program by your terminal, at which point the backlogged spaces trigger the loop exit; this makes it look like your program is only terminating on the newline condition, but it's not. You might have spotted this if you had generated some output from within your program to see how many characters it was actually processing before quitting.
You can resolve this by turning off line buffering in your terminal emulator, or by removing the ability to use spaces to terminate the loop and instead just rely on newlines — the latter is the convention as then you do not have to ask your users to configure their terminal specially to run your program: it'll already function properly in all the usual cases.
Bootnote — general advice
It's important not to assume that, if applying solution A for problem 1 doesn't immediately make your program work perfectly, that solution A must be wrong. You should consider the possibility that you also have as-yet-unknown problems 2 and 3.
It's really important to keep an open mind and gather evidence, such as writing output from your program to track its execution... or use a debugger to step through it and analyse what it is doing. As far as I can tell, you haven't really gathered any evidence at all about how your program executes… beyond cursory empirical observations, that is.

Keeping Lightness's great answer in mind, it should be noted that you're reading a single whitespace-separated token, which the built-in formatted I/O operators already do. For example, operator>>() is designed to pull out a token of input (say a number) until it reaches whitespace which is a space character and newline character.
A cleaner way of doing it would be to use the standard algorithms and classes from the standard library such as std::istream_iterator and std::accumulate():
#include <iterator>
#include <string>
#include <iostream>
#include <numeric>
int main()
{
typedef std::istream_iterator<std::string> iter_t;
iter_t it(std::cin);
int cho(0);
if (it != iter_t{})
{
auto s = *it;
cho = std::accumulate(std::begin(s), std::end(s), 0,
[] (int v, unsigned char c) { return v + c - '0'; });
}
std::cout << cho;
}
std::istream_iterator uses operator>>() internally and std::accumulate() will go through the characters, convert them to integers, and accumulate their sum.

Related

Should I handle multiple instances of cin / stdin?

Below is a little program in C++ which is supposed to act as the cat linux binutil: it gets one or several inputs as detailed in the command line arguments (possibly specifying stdin via '-') and copy them onto the standard output. Unfortunately, it shows an unintended behaviour that I cannot understand the root causes of...
Upon the following command
./ccat - test.text
I hit CTRL-D directly without passing any character. I would expect the program to display anyway the content of test.txt, but instead, the program exits without passing any more characters onto the standard output stream.
Any idea on how I should correct my code below to have the correct behaviour in this situation? Should I handle multiple instances of the standard streams (cin, cout...)? If so, do you know how this can be achieved in C++?
Thank you in advance.
/**** ccat.cpp ****/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char **argv) {
if (argc <= 1) {
cout << cin.rdbuf();
} else {
vector<string> inputs;
for (int i=1; i<argc; ++i) inputs.push_back(argv[i]);
for (auto &in: inputs) {
if (in == "-" || in == "--") {
cout << cin.rdbuf();
}
else {
ifstream *fd = new ifstream(in);
if (!fd->is_open()) cerr << "Cannot open file \'" << in << "\'\n";
else cout << fd->rdbuf();
delete fd;
}
}
}
return 0;
}
I tried the following commands in sequence:
$ ./ccat > test.txt
Let's try this text.
I would expect a correct behaviour.
$ ./ccat - test.txt # I hit CTRL-D directly without passing any character first
$ ./ccat - test.txt
But when I add some characters before hitting CTRL-D... This works fine.
But when I add some characters before hitting CTRL-D... This works fine.
Let's try this text.
I would expect a correct behaviour.
As the example shows, I would expect in any of the two cases (last two shell prompts) that test.txt gets displayed onto the standard output, but this occurs only if I inject characters through the standard input first. Hitting CTRL-D straight away makes the program exit prematurely.
That's overload 10 here;
basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb );
and it says
If no characters were inserted, executes setstate(failbit).
In other words, cout is now in an error state and will not output anything.
Doing
cout.clear();
first of all in the else branch, or last of all in the if branch, should do it.
Note that sending end-of-file to standard input is usually not something you can recover or "restart" from, so you might only be able to use one standard input "section".

Why does getline behave weirdly after 3 newlines?

I'll preface this by saying I'm relatively new to posting questions, as well as C++ in general, my title is a little lame as it doesn't really specifically address the problem I am dealing with, however I couldn't really think of another way to word it, so any suggestions on improving the title is appreciated.
I am working on a relatively simple function which is supposed to get a string using getline, and read the spaces and/or newlines in the string so that it can output how many words have been entered. After reaching the character 'q' it's basically supposed to stop reading in characters.
void ReadStdIn2() {
std::string userInput;
const char *inputArray = userInput.c_str();
int count = 0;
getline(std::cin, userInput, 'q');
for (int i = 0; i < strlen(inputArray); i++){
if ((inputArray[i] == ' ') || (inputArray[i] == '\n')){
count += 1;
}
}
std::cout << count << std::endl;
}
I want to be able to enter multiple words, followed by newlines, and have the function accurately display my number of words. I can't figure out why but for some reason after entering 3 newlines my count goes right back to 0.
For example, if I enter:
hello
jim
tim
q
the function works just fine, and returns 3 just like I expect it to. But if I enter
hello
jim
tim
bill
q
the count goes right to 0. I'm assuming this has something to do with my if statement but I'm really lost as to what is wrong, especially since it works fine up until the 3rd newline. Any help is appreciated
The behaviour of the program is undefined. Reading input into std::string potentially causes its capacity to increase. This causes pointers into the string to become invalid. Pointers such as inputArray. You then later attempt to read through the invalid pointer.
P.S. calculating the length of the string with std::strlen in every iteration of the loop is not a good idea. It is possible to get the size without calculation by using userInput.size().
To fix both issues, simply don't use inputArray. You don't need it:
for (int i = 0; i < userInput.size(); i++){
if ((userInput[i] == ' ') || (userInput[i] == '\n')){
...

Why it works when I type multiple characters in a character variable?

I am a new C++ user.
My code is as following:
#include <iostream>
using namespace std;
int main()
{
int option = 1;
char abstract='a';
while(option == 1){
char temp;
cin>> temp;
abstract = temp;
cout << abstract;
option = 1;
if(abstract == '!'){
option = 0;
}
}
return 0;
}
And when I typed something like: abcdefg
all the characters are on the screen,why? It's just because of the compiler?
In fact, only one character at a time is stored in your char. cin>>temp; reads a single char at a time since more characters would not fit there. The loop simply reads and prints one character after the other.
As a visualization hint, try echoing your characters with cout<<abstract<<endl;. You will see a single character per line/iteration.
Your terminal does not restrict the number of characters typed in , that's why you can type as many as you want. Your c++ compiler would read only one of the characters because 'temp' is of type char. you can type an 'if' statement to check the number of characters typed in the terminal
Because of the while loop, which processes each character in turn. Not sure what you expected to happen.
Print it out with delimiters to see that there's never more than a single character printed per iteration:
cout << "'" << abstract << "'";
The terminal window itself is responsible for reading the characters and echoing them back to the screen. Your C++ program asks the terminal for characters and, in this sort of program at least, has no effect on how those characters are displayed.

Simple C++ not reading EOF

I'm having a hard time understanding why while (cin.get(Ch)) doesn't see the EOF. I read in a text file with 3 words, and when I debug my WordCount is at 3 (just what I hoped for). Then it goes back to the while loop and gets stuck. Ch then has no value. I thought that after the newline it would read the EOF and break out. I am not allowed to use <fstream>, I have to use redirection in DOS. Thank you so much.
#include <iostream>
using namespace std;
int main()
{
char Ch = ' ';
int WordCount = 0;
int LetterCount = 0;
cout << "(Reading file...)" << endl;
while (cin.get(Ch))
{
if ((Ch == '\n') || (Ch == ' '))
{
++WordCount;
LetterCount = 0;
}
else
++LetterCount;
}
cout << "Number of words => " << WordCount << endl;
return 0;
}
while (cin >> Ch)
{ // we get in here if, and only if, the >> was successful
if ((Ch == '\n') || (Ch == ' '))
{
++WordCount;
LetterCount = 0;
}
else
++LetterCount;
}
That's the safe, and common, way to rewrite your code safely and with minimal changes.
(Your code is unusual, trying to scan all characters and count whitespace and newlines. I'll give a more general answer to a slightly different question - how to read in all the words.)
The safest way to check if a stream is finished if if(stream). Beware of if(stream.good()) - it doesn't always work as expected and will sometimes quit too early. The last >> into a char will not take us to EOF, but the last >> into an int or string will take us to EOF. This inconsistency can be confusing. Therefore, it is not correct to use good(), or any other test that tests EOF.
string word;
while(cin >> word) {
++word_count;
}
There is an important difference between if(cin) and if(cin.good()). The former is the operator bool conversion. Usually, in this context, you want to test:
"did the last extraction operation succeed or fail?"
This is not the same as:
"are we now at EOF?"
After the last word has been read by cin >> word, the string is at EOF. But the word is still valid and contains the last word.
TLDR: The eof bit is not important. The bad bit is. This tells us that the last extraction was a failure.
The Counting
The program counts newline and space characters as words. In your file contents "this if fun!" I see two spaces and no newline. This is consistent with the observed output indicating two words.
Have you tried looking at your file with a hex editor or something similar to be sure of the exact contents?
You could also change your program to count one more word if the last character read in the loop was a letter. This way you don't have to have newline terminated input files.
Loop Termination
I have no explanation for your loop termination issues. The while-condition looks fine to me. istream::get(char&) returns a stream reference. In a while-condition, depending on the C++ level your compiler implements, operator bool or operator void* will be applied to the reference to indicate if further reading is possible.
Idiom
The standard idiom for reading from a stream is
char c = 0;
while( cin >> c )
process(c);
I do not deviate from it without serious reason.
you input file is
this is fun!{EOF}
two spaces make WordCount increase to 2
and then EOF, exit loop! if you add a new line, you input file is
this is fun!\n{EOF}
I took your program loaded it in to visual studio 2013, changed cin to an fstream object that opened a file called stuff.txt which contains the exact characters "This is fun!/n/r" and the program worked. As previous answers have indicated, be careful because if there's not a /n at the end of the text the program will miss the last word. However, I wasn't able to replicate the application hanging in an infinite loop. The code as written looks correct to me.
cin.get(char) returns a reference to an istream object which then has it's operator bool() called which returns false when any of the error bits are set. There are some better ways to write this code to deal with other error conditions... but this code works for me.
In your case, the correct way to bail out of the loop is:
while (cin.good()) {
char Ch = cin.get();
if (cin.good()) {
// do something with Ch
}
}
That said, there are probably better ways to do what you're trying to do.

Detecting space in a file in c++

Hi i was just wondering if anybody could help me i am reading characters from a file then inserting them into a map i have the code working i was just wondering how do i detect if a space is in the file cause i need to store the amount of times a space occurred in a file any help would be great thanks.
map<char, int> treeNodes; //character and the frequency
ifstream text("test.txt");
while(!text.eof())
{
text >> characters;
//getline(text,characters);
cout << characters;
if(treeNodes.count(characters) == 0)
{
if(isspace (characters))
{
cout << "space" << endl;
}
else
treeNodes.insert(pair<char,int>(characters,1));
}
else
{
treeNodes[characters] += 1;
}
}
Formatted input, i.e. when using the right shift operator>>() skips leading whitespace by default. You can turn this off using std::noskipws but depending on what sort of things you want to read it won't be a very happy experience. The best approach is probably using unformatted input, i.e. something like std::getline() and split the line on space within the program.
If you just want to count the number of times any particular character occurred, you probably want to use std::istreambuf_iterator<char> and just iterate over the content of the stream (this code also omits some other unnecessary clutter):
for (std::istreambuf_iterator<char> it(text), end(); it != end; ++it) {
++treeNodes[*it];
}
BTW, you never want to use the result of eof() for something different than determining whether the last read failed because the stream has reached its end.
couldn't you just cast the char to an int and test if it is equal to the ascii value of a space?