while loop (cin>>)

Hi all, i am stumped with this problem, its very simple yet i cannot find solution anywhere. Please help.
Code works and it outputs things from while loop as it should when i press enter but it doesnt output last sentence outside of while loop (on the end). When pressing enter nothing happens.
Is there solution for beginners? the one i could understand at this point. (Just started to read Bjarne book)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "std_lib_facilities.h"

int main()
{
	string sen="start";
	string prev = "previous";
	int order = 1;
	int nwords = 0;

	cout << "Enter few words: \n";
	
	while (cin >> sen)
	{
		if (sen == prev)
		{
			cout << "\n" << order << ". Word " << sen << " is repeating. ";
			nwords++;
		}
		prev = sen;
		order++;
		
	}
	cout << "\nNumber of repeated words is: " << nwords << ".";
	return 0;
}
Last edited on
Well you have to make the while loop terminate somehow.

As written, the only way is to signal the EOF condition from the console.
This you typically do by pressing ctrl-d (Unix/Linux) or ctrl-z (Windows).

Or you could add inside the loop
 
if ( sen == "STOP" ) break;

Then all you have to do is type in whatever word you chose to end the loop.
try
cout << '\n';
or
cout << flush;

How do You stop the loop?
Hello tinaHR,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



salem c has explained how you can fix the problem with the while loop.

I have not progressed that far into Stroustrup's book that far, so I am not sure why he is using "std_lib_facilities.h" instead of teaching the proper header files. This may be easier right now, but it is not teaching you what you should be learning.

You need two header files:
1
2
#include <iostream>  // <--- For std::cin, std::cout and std::endl.
#include <string>  // <--- For std::string. 

Learning what header files a program will need is part of the learning process and will do you better than relaying on something like #include "std_lib_facilities.h" which is likely to include more header files than you know about or even need.

When you write std::string sen="start"; it is not necessary to initialize this variable because std::string sen"; is created as an empty variable with no length. And since the first thing you do with this variable is while (std::cin >> sen) this overwrites your initialized variable.

Another thing to keep in mind is that std::cin >> sen, AKA formatted input, will take from the input buffer what you type up to a white space or new line whichever comes first. Leaving anything else left in the input buffer. If this happens the program will take, from what is left in the input buffer, what it can and not the keyboard. Which means the while loop will loop a second time or more until it finds the new line character. Sometimes this comes in handy, but not always what you want.

Overall the style of your code is good. I would suggest adding a couple of blank lines. And the blank line between "order++;" and the closing brace of the while loop is not needed.

If it has not been mentioned in the book yet the compiler does not care about white space or blank lines, bur someone, including you, does care about blank lines and white space as it makes the code easier to read and hat is the bigger point making it easier to read and understand.

This is a suggestion of what you code could look like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//#include "std_lib_facilities.h"
#include <iostream>
#include <string>

int main()
{
	std::string sen = "start";
	std::string prev = "previous";
	int order = 1;
	int nwords = 0;

	std::cout << "Enter few words: \n";

	while (std::cin >> sen)
	{
		if (sen == prev)
		{
			std::cout << "\n" << order << ". Word " << sen << " is repeating. ";
			nwords++;
		}

		prev = sen;

		order++;
	}

	std::cout << "\nNumber of repeated words is: " << nwords << ".";

	return 0;
}

I am not saying that yo have to do it this way, but it does break up the code and make it easier to read.

Hope that helps,

Andy
Thanks everyone,

if ( sen == "STOP" ) break; worked splendid.

The reason i was confused was that i thought when i pressed enter that loop was ''done'' since then ive got output with results. Now when you mentioned it i tested it out of curiosity and the loop was just continuing with counting(order++ etc) instead of finishing or restarting the loop (after pressing enter) which was interesting. How does that work? does it read from cin, stores that somewhere and then when we press enter do the calculation and output or does is store calculations and then outputs it when we press enter? i know it doesnt make sense and it might be ridiculous question but without much experience its difficult to see the whole picture clearly like experienced programmers do (and many questions looks silly once we know the answer).

Thank you for the <formatting> tip, i havent realised it was changed after copy-pasting. I used to have a bit of OCD on making the code look neat lol, now i see the that visual is indenting automatically which is quite useful.

I did study software engineering like 5 years ago and was good at it because i liked it, but only for about 1 year before i had to stop so havent got that far, i wasnt even sure if i will ever go back to it again but in all those years wondering if i wanted to do it i realised if i didnt want to, if it wasnt my passion i wouldnt think through it over and over so i am starting from zero and learning by myself using Bjarne book. (wasnt planning on writing my whole life story on such simple question but got excited about learning again lol).

I think he uses std_lib_facilities because he starts very early with simplest examples like hello, world! and will explain later libraries so not to confuse the very beginners.

The reason i initialized that string was that i read somewhere in the book that many errors can come from not initializing, but i guess he didnt meant that about string variables.

I do have one non related question. How much of this stuff that we learn on the beginning is actually used? (for, while, vectors, sorting, classes, writing your functions etc). I mean is it just small proportion of a program? the reason im asking is when i see actual code somewhere its like looking at something ive never seen before and looks so complicated that makes me wonder if i will be able to learn all that (and in how many decades).

Also how does actual coding looks like, i mean how does one job or assignment looks like? I cannot find any specific examples. We learn in school about fors and ifs, we do sorting and hypothetical examples but okay so what do i do with it? what will (hopefully) employer/buyer in future ask me to do? i know that this is a bit stupid question as every single thing is different from web, apps to infinity so every assignment is different but to me at the moment it looks so abstract that i cant even have idea how it might look like (it will probably get clearer as i learn more but its a bit shame that we are supposed to learn for the job which we have no idea how it looks like, in the schools most of other studies have practical hours in actual companies to prepare and get the idea about the job you supposed to do in future, except in software engendering, in my country at least).

Sorry about long text and i will completely understand if you dont answer lol, thank your for the solution for my problem and for advices.

Tina


closed account (367kGNh0)
You can also mark your post as solved, as the matter is closed. It should be relatively easy at the top of the post the options should appear for you
Hello Tina,

I will do my best to answer your questions.

The reason i was confused was that i thought when i pressed enter that loop was ''done''

No, based on the while condition "std::cin >> sen". Only the input was done when you pressed "Enter". As long as "std::cin" remains in a good state the whole condition is evaluated as true and you enter the while loop. This is where salem c's suggestion, if ( sen == "STOP" ) break;, comes in. You are checking if what was entered is equal to the stop sentinel, in this case "STOP", and if it is true then the "break" statement will break out of the while loop.

This may be a simple explanation. C++ as with C does not deal with the keyboard or screen directly. When you include "iostream", the high level header file, it includes "istream" which includes "ostream" which includes "ios" which includes "xlocnum" which includes several other header files to get to the low level code that can deal with the keyboard or the screen. In the end all you have to worry about is the "iostream" lets you use "std::cin" to use the keyboard and "std::cout and std::endl" to use the screen for output. At least this is what I see with VS, used more often than (visual) or (Visual Studio).

Next what you type on the keyboard does not go directly into the variable following "std::cin", but into an input buffer waiting you you to press enter. Then it will try to extract from the input buffer what it can into the variable. This is where formatted input of std::cin >> sen; and tsd::getline(...); makes a difference.

This may also help. A while loop, do/while loop, if statement and the middle part of a for loop all work on the principal of false (0), zero, or true (1). So, whatever is in the condition part has to evaluate to either false or true. In the case of std::cin >> sen what is being checked here is the state bits of the stream, namely the (good) bit. As long as the good bit is (1) you will enter the while loop until this bit is changes. The problem is that you have no way to change the state bits unless you use salem c's suggestion of
pressing ctrl-d (Unix/Linux) or ctrl-z (Windows).
i know it doesnt make sense and it might be ridiculous question
No actually it does make sense and it is a very good question for a beginner.

I recently purchased "Stroustrup's", but I do not think I am as far along as you are. He may have a point for the "std_lib_facilities.h" and I can understand using it until it is explained later, but I feel it is more of a stumbling block than a help. It is like the line using namespace std;. This may work in the beginning, but eventually it becomes a problem. Also people are told to use this, but not about the potential problems or what it is actually doing.

As for initializing variables. Variables like char, short, int, double along with their unsigned versions are assigned space on the stack when the program compiles and only space. What happens is that the variable will try to use whatever is left in that particular part of memory and make it fit into the particular type of variable as defined. This is referred to as a garbage value. On my computer an "int" usually has the garbage value of "-858993460" and a double "-9.2559631349317831e+64". Your computer may be different. Any way not something you want to work with.

Personally I feel it is a good idea to initialize your variables when they are defined. Also this is not always necessary if you give the variable a value not long after it is defined. It is when you try to use a variable before it is given a proper value.

The exception would be strings, vectors, lists, queues and any other type that is considered a type of container. These variable types are empty when they are defined and do not need initialized unless you need it to contain something like std::string prev = "previous";.

You used the word "visual". I took this to mean VS (Visual Studio). I do not know which version you are using, but would guess it is new enough to use the C++11 standards. In that case you can define an initialize a variable as: int num{};. The empty {}s will set the variable to (0) zero. Other forms of an "int" to (0). A "char" to '\0" and a double to "0.0".

How much of this stuff that we learn on the beginning is actually used?

All of it. First you have to learn the basics before yo can do it better. Also once you understand how the basics work other code will not be as intimidating. Learning slow and with repetition is a good way to learn. I once took an online course in "Python" where the instructor said that by typing the same thing many times you learn partly be repetition. It does have its use.

As for what or how a program should look it really depends on the program and what you are trying to do. There is no format to the program only what to put where. If you are unsure just ask.

Hope that helps,

Andy
Thank you Andy for your time and detailed explanations :)
Any time.
Topic archived. No new replies allowed.