Does `cin` produce a newline automatically? - c++

Let's consider the following code:
#include<iostream>
int main()
{
std::cout<<"First-";
std::cout <<"-Second:";
int i;
std::cin>>i;
std::cout<<"Third in a new line.";
while(1){}
}
The output when value 4 is given to i is:
First--Second:4
Third in a newline
cout doesn't print any newline. But after I input any value(4) for i a newline is printed. There could be two possible reasons for this:
The Enter key I press after typing a numerical value for i is printed as a newline.
cin automatically generates a newline.
Although the first reason seems more reasonable but the reason, I am thinking 2nd reason could also be true, is because after Third is printed when I press Enter no new line is printed even the program continue to run because of while(1)--which means the console window doesn't print a newline when Enter key is pressed. So it seems like cin automatically prints a newline.
So, why is the newline being generated after I give input to cin? Does cin automatically prints a newline?

The number and newline you entered is printed by the console software. cin won't print anything in my understanding.
Try giving some input via redirect or pipe, and I guess you will see no new line printed.
For example:
$ echo 4 | ./a.out
First--Second:Third in a new line.
where $ is the prompt and echo 4 | ./a.out(Enter) is your input.

Check this out: http://ideone.com/tBj1uS
You can see there that input and output are separated.
stdin:
1
2
stdout:
First--Second:Third in a new line.
Which means, that the newline is produced by the Enter key and is a part of the input, not the output.

If someone will have the same problem, I was able to solve it like this:
string ans1;
getline(cin, ans1);
ans1.erase(remove(ans1.begin(), ans1.end(), '\n'),
ans1.end());
int ans1int = atoi(ans1.c_str());
Basically, it works by deleting all the newline characters in the string, and then ,aking it integer or whatever else you need. Also you will need algorithm library for it
It's not that elegant, but hey, it works!

Related

C++ string input without newline in console

As I wrote in the title, I would like to get a string input (with simple methods) without produce a newline in the console.
I searched in the web for more than an hour and couldn't find an answer to this simple question...why?
My program will be a simple Vocabulary trainer: I would like to write a French word and its translation in German into a text file. Therefore I first want to get the French word with
getline(cin, word_french);
Then I would like to print a " - " and after that I want to get the German word.
The problem is that after writing the French word, the "enter" will produce a newline in the console. So how not to get a newline after the string input?
I would like to appear it like this in the console:
(inserted french word) - (inserted german word)
string word_french, word_german;
cout<<"Beginn with the french word"<<endl;
ofstream out;
out.open("test.txt", ios::app);
std::cin.sync(); //clear buffer
getline(cin,word_french); //here the enter will produce the new line...
out<<"\n" +word_french;
cout<<" - ";
getline(cin, word_german);
out<<";"+word_german;
out.close();
Please try to keep it simple...

[c++]while(cin.get(str,size).get())... why infinit looping,rather than quit if i give a blank line

it's a c++ question.
char str[10];
while(cin.get(str,10).get())
...
cin.clear();
i hope when i give just the enter key, the while loop would end due to that the cin.get(str,size) would fail encountering the blank line. but when I add a .get() behind aim to read up the following \n, the while loop just keep looping when i give a blank line?
is it that the .get() causes the judgement true override the cin.get(str,size)'s false?
cin.get(str,10) Extracts characters from the stream and stores them in str as a c-string, until either 9 characters have been extracted or the delimiting character is encountered, not "gets 10 and fails if it cant, because the line ended."
This will basically never "fail" until you get to the end of file.
You will have to capture the line and test its length separately (probably not in the same expression)

Detecting end of input using std::getline

I have a code with the following snippet:
std::string input;
while(std::getline(std::cin, input))
{
//some read only processing with input
}
When I run the program code, I redirect stdin input through the file in.txt (which was created using gedit), and it contains:
ABCD
DEFG
HIJK
Each of the above lines end with one newline in the file in.txt.
The problem I am facing is, after the while loop runs for 3 times (for each line), the program control does not move forward and is stuck. My question is why is this happening and what can I do to resolve the problem?
Some clarification:
I want to be able to run the program from the command line as such:
$ gcc program.cc -o out
$ ./out < in.txt
Additional Information:
I did some debugging and found that the while loop actually is running for 4 times (the fourth time with input as empty string). This is causing the loop to program to stall, because the //some processing read only with input is unable to do its work.
So my refined question:
1) Why is the 4th loop running at all?
Rationale behind having std::getline() in the while loop's condition
must be that, when getline() cannot read any more input, it returns
zero and hence the while loop breaks.
Contrary to that, while loop
instead continues with an empty string! Why then have getline in the
while loop condition at all? Isn't that bad design?
2) How do I ensure that the while doesn't run for the 4th time without using break statements?
For now I have used a break statement and string stream as follows:
std::string input;
char temp;
while(std::getline(std::cin, input))
{
std::istringstream iss(input);
if (!(iss >>temp))
{
break;
}
//some read only processing with input
}
But clearly there has to be a more elegant way.
Contrary to DeadMG's answer, I believe the problem is with the contents of your input file, not with your expectation about the behavior of the newline character.
UPDATE : Now that I've had a chance to play with gedit, I think I see what caused the problem. gedit apparently is designed to make it difficult to create a file without a newline on the last line (which is sensible behavior). If you open gedit and type three lines of input, typing Enter at the end of each line, then save the file, it will actually create a 4-line file, with the 4th line empty. The complete contents of the file, using your example, would then be "ABCD\nEFGH\nIJKL\n\n". To avoid creating that extra empty line, just don't type Enter at the end of the last line; gedit will provide the required newline character for you.
(As a special case, if you don't enter anything at all, gedit will create an empty file.)
Note this important distinction: In gedit, typing Enter creates a new line. In a text file stored on disk, a newline character (LF, '\n') denotes the end of the current line.
Text file representations vary from system to system. The most common representations for an end-of-line marker are a single ASCII LF (newline) character (Unix, Linux, and similar systems), and as sequence of two characters, CR and LF (MS Windows). I'll assume the Unix-like representation here. (UPDATE: In a comment, you said you're using Ubuntu 12.04 and gcc 4.6.3, so text files should definitely be in the Unix-style format.)
I just wrote the following program based on the code in your question:
#include <iostream>
#include <string>
int main() {
std::string input;
int line_number = 0;
while(std::getline(std::cin, input))
{
line_number ++;
std::cout << "line " << line_number
<< ", input = \"" << input << "\"\n";
}
}
and I created a 3-line text file in.txt:
ABCD
EFGH
IJHL
In the file in.txt each line is terminated by a single newline character.
Here's the output I get:
$ cat in.txt
ABCD
EFGH
IJHL
$ g++ c.cpp -o c
$ ./c < in.txt
line 1, input = "ABCD"
line 2, input = "EFGH"
line 3, input = "IJHL"
$
The final newline at the very end of the file does not start a newline, it merely marks the end of the current line. (A text file that doesn't end with a newline character might not even be valid, depending on the system.)
I can get the behavior you describe if I add a second newline character to the end of in.txt:
$ echo '' >> in.txt
$ cat in.txt
ABCD
EFGH
IJHL
$ ./c < in.txt
line 1, input = "ABCD"
line 2, input = "EFGH"
line 3, input = "IJHL"
line 4, input = ""
$
The program sees an empty line at the end of the input file because there's an empty line at the end of the input file.
If you examine the contents of in.txt, you'll find two newline (LF) characters at the very end, one to mark the end of the third line, and one to mark the end of the (empty) fourth line. (Or if it's a Windows-format text file, you'll find a CR-LF-CR-LF sequence at the very end of the file.)
If your code doesn't deal properly with empty lines, then you should either ensure that it doesn't receive any empty lines on its input, or, better, modify it so it handles empty lines correctly. How should it handle empty lines? That depends on what the program is required to do, and it's probably entirely up to you. You can silently skip empty lines:
if (input != "") {
// process line
}
or you can treat an empty line as an error:
if (input == "") {
// error handling code
}
or you can treat empty lines as valid data.
In any case, you should decide exactly how you want to handle empty lines.
Why is the 4th loop running at all?
Because the text input contains four lines.
The new line character means just that- "Start a new line". It does not mean "The preceeding line is complete", and in this test, the difference between those two semantics is revealed. So we have
1. ABCD
2. DEFG
3. HIJK
4.
The newline character at the end of the third line begins a new line- just like it should do and exactly like its name says it will. The fact that that line is empty is why you get back an empty string. If you want to avoid it, trim the newline at the end of the third line, or, simply special-case if (input == "") break;.
The problem has nothing to do with your code, and lies in your faulty expectation of the behaviour of the newline character.
Finale:
Edit: Please read the accepted answer for the correct explanation of the problem and the solution as well.
As a note to people using std::getline() in their while loop condition, remember to check if it's an empty string inside the loop and break accordingly, like this:
string input;
while(std::getline(std::cin, input))
{
if(input = "")
break;
//some read only processing with input
}
My suggestion: Don't have std::getline() in the while loop condition at all. Rather use std::cin like this:
while(std::cin>>a>>b)
{
//loop body
}
This way extra checking for empty string will not be required and code design is better.
The latter method mentioned above negates the explicit checking of an empty string (However, it is always better to do as much explicit checking as possible on the format of the input).

Why must type getline(cin, string) twice?

need your help in getting user inputs.
I want users to type a string that has spaces.
i cant use cin>>variable as the space in between makes the problem go wrongly.
if i use getline(cin,string_variable) it works correctly. but i need to type twice in order to make it work proberly.
cout<<"Enter movie name";
getline(cin, mvName);
getline(cin, mvName);
Is there a better way to get user input than this or is there any other codes to type rather than typing the getline twice? Pls advice.
When switching between formatted input using in >> value and unformatted input, e.g., using std::getline(in, value) you need to make sure that you have consumed any whitespace you are not interest in. In you case there is probably a newline in the buffer from a prior input. Assuming you are nit interested in leading whitespace the easiest approach is to use something like this:
if (std::getline(std::cin >> std::ws, mvName)) {
process(mvName);
}
BTW, you should always check that your input was successful.
I had no issues using:
char mvName[32];
cin.getline(mvName, 32);
And I only had to call it once, again with no issues.
Maybe you just forget to add \n in your prompt message:
cout<<"Enter movie name:\n";
But if you want skip empty lines - do this:
// skip empty lines
while (cin >> mvName && mvName.empty());
// here mvName contains non empty string or it is empty because of error in reading
....
As the question contains no new-line character I suspect you hit enter to move down from the "Enter movie name" question? This would put a blank line into stdin, which the first getline() would read and then second getline() would read your entered text.
To remove the requirement of typing the initial new-line character just add it to the question's string literal:
std::cout<< "Enter movie name:\n";
cout<<"Enter movie name";
getline(cin, mvName);
Works fine!
Maybe you had to use getline(cin, mvName); twice was because you inputted some character into the first getline(cin, mvName); like Space, Enter, etc.

Flex(Lex) output not right

So I have to make a flex program that matches numbers, floats, symbols, and comments.
The regular expressions are in the file.
The flex.l file http://pastebin.com/iuJ8WW6m
The weird part is the output.
Lets say I'm giving it:
0 0.0 323 323.4 1.3.4
variable another_variable
"string"
;comment
69
This is the output:
Number: -->0<--
Float: -->0.0<--
Number: -->323<--
Float: -->323.4<--
Float: -->1.3<--
Number: -->4<--
Symbol: -->variable<--
<--bol: -->another_variable
String: -->"string"<--
<--ment: -->;comment
Number: -->69<--
Why is the output at "another_variable" like this <--bol: -->another_variable ?
I know some c/c++ and for me this makes 0 sense.
Same goes for <--ment: -->;comment
Apparently it takes the 3 last character (<--) and places them on top of the first 3(Com), But why?
If i give it only
;comment
The output is "Comment: -->;comment<--", As soon as I insert a new line after it, it messes up again. I also tried the same with printf and using ECHO, but the result is the same.
Help, thanks!
I suspect that part of the the newline sequence that follows the recognized comment or symbol is being captured into yytext, and hence echoed back in your debug trace.
Try adding \r to the character class, like so:
SYMBOLS [a-zA-Z][^\,\.\"\(\) \n\t\r]*
COMMENTS ";"[^\n\r]*
In any event, you might want to pipe your debug output into a file so that you can examine it characterwise, with a tool like od.