I've been trying to make a program which requires me to read symbols until a new line. I saw a lot of people suggested getline() in similar problems, but
I want to know if there is any other way to do it, mainly because of the way my code works so far.
#include <iostream>
#include <string>
int main()
{
std::string str;
while(true)
{
std::cin >> str;
std::cout << str << " ";
//some actions with token
}
}
The thing I find interesting about this code is that it first reads all the inputs, and then when I press Enter, it writes them all, for example, if I input
1 2 3 a b c
I get the output after I press enter. So is there a way to use that to my advantage and only take one line of input?
You are seeing the output behavior after enter due, most likely, to the buffer being flushed. In most cases I'm aware of, this is just an artifact of how you are interacting with the stdout of your terminal, and shouldn't change how stdin is read at all.
Your best bet is definitely istream::getline, which has a great example on C++ Reference:
// istream::getline example
#include <iostream> // std::cin, std::cout
int main () {
char name[256], title[256];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256);
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256);
std::cout << name << "'s favourite movie is " << title;
return 0;
}
For more information on buffer flushing, I found a decent SO question on it: What does flushing the buffer mean?
Related
I'm trying to copy user input text into a file and its doing that its just also adding a newline before the text starts any ideas how to make it not do that?
getline(cin, userInput);
while (userInput != endWrite) {
storyTime << userInput << endl;
getline(cin, userInput);
}
storyTime.close();
return 0;
}
Your code is incomplete, so it's impossible to be absolutely certain what may be going on--at first glance, my immediate guess would be that what you're seeing may result from some code you didn't quote. For one obvious possibility you might be asking the user for the name of the file where you're going to write the output:
std::string outputName;
std::cout << "Enter output file name: ";
std::cin >> outputName;
std::ofstream storyTime(outputName);
//...
In this case, the std::cin >> outputName; reads the filename--but you had to press the enter key to get it to read that, and that press of the enter key will leave a new-line in the input, so when you start the loop afterwards, it'll be read as a newline preceding the text the user enters afterwards.
Aside
Other than that, I'd normally try to keep the code somewhat simpler:
while (std::getline(std::cin, userInput)) {
storytime << userInput << '\n';
}
As a really general rule of thumb, I'd advise that a formatted read from a text file (using either std::getline or some operator>>) be as the condition of an if, while, or whatever. Doing so habitually makes it much easier to write input loops that process files correctly.
Demo
Just for what it's worth, here's some working code that doesn't insert an extra new-line:
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string userInput;
std::string filename;
std::cout << "Please enter file name: ";
std::getline(std::cin, filename);
std::ofstream output{filename};
while (std::getline(std::cin, userInput)) {
output << userInput << '\n';
}
}
I am trying to read someone's full name in C++, and obviously that would have spaces (like "John Doe"). The easiest way I can do this (since cin by default breaks at whitespace) is with getline(cin, str) where "str" is the variable.
However, when doing this, it starts reading text on the next line. Instead of this:
Please enter your full name > John Doe
You get
Please enter your full name >
John Doe
Here's the code that produces the result:
string fullName;
cout << "Please enter your full name >";
getline(cin, fullName);
Is there any way I can read the full line and still keep it on the same line?
Without a Minimal, Complete, Verifiable Example, it is difficult to diagnose the issue you're having. However, I am able to produce code that reads a line of input from the user without breaking the previous "Enter your name>" line:
#include <iostream>
#include <string>
int main()
{
std::string str;
std::cout << "Please enter your full name > ";
std::getline(std::cin, str);
std::cout << "Hello " << str << std::endl;
return 0;
}
If you've gotten into the habit of appending all std::cout lines with std::endl, you may have neglected to omit it that time.
I just want to write a simple script that asks for someone's name and prints it out. But for some reason, when I use the string data type it just kind of, does nothing.
Here is the code and output if I use a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Please give me your name: ";
getline(cin, name);
cout << "Hello " << name << endl;
return 0;
}
As you can see, it just runs the .exe and nothing happens. However if I take the C approach to strings and use a character array and also don't use getline(), it works fine (but doesn't skip the '\0' character):
#include <iostream>
#include <string>
using namespace std;
int main()
{
//string name;
char name[15];
cout << "Please give me your name: ";
//getline(cin, name);
cin >> name;
cout << "Hello " << name << endl;
return 0;
}
I have tried a few other approaches and all have worked fine. For some reason, making the variable name as a string data type makes it behave weirdly. I tried looking around some C++ based books and the web but no one seems to have
had this problem.
I'm just going to add this for clarification, I checked to see if the program was just executing too fast for me to see what was going on. It is not doing that, it even skips the part where it is supposed to wait for input.
I am using Visual Studio Code to write the programs and MinGW to compile. I took my code and ran it over at https://www.onlinegdb.com/ and it worked as expected:
Could this possibly be a Windows or Command Prompt problem?
Depending on STL implementation and OS, std::cout may be buffering data in memory. It typically does not flush buffered data to console until either:
a threshold is reached
a '\n' character is output
std::cout.flush() is called (which includes outputting std::endl, which calls flush() after writing a line break).
Try calling std::cout.flush() (directly, or via std::flush) after outputting the prompt and before reading the name:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Please give me your name: " << flush;
getline(cin, name);
cout << "Hello " << name << endl;
return 0;
}
I'm creating a text editor and here is its code:
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <conio.h>
int main()
{
system("cls"); system("COLOR F0");
std::string input;
static int lineNo=0;
while(true)
{
lineNo+=1;
std::cout << lineNo << "\t";
input=="{" ? std::cout << "\t" : std::cout << "";
input=="(" ? std::cout << "\t" : std::cout << "";
input=="[" ? std::cout << "\t" : std::cout << "";
std::getline(std::cin, input);
}
return 0;
}
I want to create an auto-completion tool for the brackets which enters the closing bracket instantly after the opening brace has been typed. Please help me as I am just a beginner.
You could use getch() function from conio.h library for scanning a single character only.You can declare a character variable and scan for braces like this.
char in;
in=getch();
if(in=="{")
{
//Write your code according to your uses.
}
std::cin is your program's standard input. It does not (in general) mean "the user's keyboard" or even "input to the terminal" or anything like that. How you get stuff from cin depends on how things are being written to your standard input, which typically does not happen character by character. Often your terminal only sends data to a program's standard input after a newline (after the user presses enter), in which case there's no way for you to get to that data beforehand through cin.
For what you're describing, you'll need to use (as Joachim Pileborg pointed out) platform-specific functionality, such as PeekConsoleInput on Windows. You may also find GetAsyncKeyState useful.
I began programming on C++ some days ago and something is really getting me troubles:
whenever I enter the number, the program ends.
Code:
using namespace std;
int main()
{
int entry;
cout << "Write a number: ";
cin >> entry;
cout << entry;
cin.get();
return 0;
}
I need some help here so my programs could run right.
By right I mean to output the number after ending... but it just ends after I enter the number and press enter It does not print it.
UPDATE:
For the sake of the ones who didn't understood what I was meaning (sorry for my english)
Ok let me explain.
-So the program is suposed to get the values from the keyboard right.
-I enter a number let´s say is 6, ok now I press enter.
-Alright now the number is supposed to be output on the screen, but this doesn´t happen because the program closes too fast.
But this was solved actually, by adding a second cin.get(); or by adding a cin.ignore(); after each data input petition.
Here's a slightly improved version that might be closer to what you wanted:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
int n;
std::string line;
while (true)
{
std::cout << "Please enter an integer: ";
if (!(std::getline(std::cin, line))) { return 1; /* error! */ }
std::istringstream iss(line);
if (iss >> n) { break; }
}
std::cout << "Thank you. You said: " << n
<< "\n\nPlease press Enter to quit.";
std::getline(std::cin, line);
}
The error condition in the getline is triggered when the input stream is closed or otherwise terminated before another line could be read (e.g. if you hit Ctrl-D on the console). The token extraction into n fails until you enter a valid integer, and the loop will continue looping until this happens.
All you need to do is consume the newline that is left over after reading the integer.
This happens in java as well.
using namespace std;
int main()
{
int entry;
cout << "Write a number: ";
cin >> entry;
cout << entry;
cin.get(); //Consume newline
cin.get();
return 0;
}
get() reads one and only one character from the stream, so it's perfectly normal that the program ends after you enter your number.
Have a look either at the std::basic_istream<>::getline() method or, easier, std::getline() which doesn't require a dynamic buffer.
If you need more information about basic IO in C++, you can read the following documentation : Basic Input/Output - C++
Update
Like stated in the comments, I missunderstood the question, I was initially thinking that only one digit was read into the variable.
After reading carefully again, I'm unable to understand what the problem is.
The reason for this is youre using
cin.get();
return 0;
at the end of the program , the cin.get() reads the number you entered then goes straight to return 0; thus ending the program.
to stop this you can add an extra cin.get(); before return 0;
or use
system("Pause");
before return 0; instead