there's an extra newline before text ofstream c++ - c++

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';
}
}

Related

Read string until new line in C++ without getline

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?

How do I correctly use "getline(cin, input);"

I am writing a program that is to convert text that a user gives. I have tried this method by itself in a test program and it works perfectly; however when I try to implement it into the larger program, the user cannot give the program an input to store. The relevant code is as follows:
int main()
{
string str = "NULL";
int mappings = 0;
readMappings(mappings);
receiveInput(str);
displayInput(mappings, str);
return 0;
}
void readMappings(int &count)
{
ifstream readMappings; // Creates the function "readMappings"
string filename; // Generates the filename variable to search for mapping document
cout << "Enter the filename of the mapping document: ";
cin >> filename; // User enters filename
readMappings.open(filename); // "readMappings" function opens the given mappings document
while (!readMappings.is_open())
{
cout << "Unsble to open file. Please enter a valid filename: "; // If the user enters an invaled filename, the program will ask again
cin >> filename;
readMappings.open(filename);
}
if (readMappings.good()) // Mapping document is successfully opened
{
readMappings >> count; // Reads first line
}
readMappings.close(); // If everything fails in this function, the document will close
}
void receiveInput(string &input)
{
char correctness;
do {
cout << "\nPlease enter the text you would like to be converted to NATO:\n";
getline(cin, input);
cout << "You are about to convert: \"" << input << "\".\nIs this correct? (Y/N)" << endl;
cin >> correctness;
} while (correctness == 'N' || correctness =='n');
}
I thought it may have been the program waiting for another input from the user so I added a variable I assumed it would already fill, but it did not fix my solution. In my opinion, the problem is in the receiveInput function, but I could be wrong. Thanks in advance for any assistance.
Also, I am using function prototypes with correct reference variables.
I see two problems:
1) You're not checking for an EOF condition, after invoking std::getline().
2) You are mixing together both std::getline and the >> operator. Now, there's actually nothing technically wrong with that, but both std::getline and the >> operator have very nuanced semantics, when it comes to error checking and input consuming, that you need to get 100% right, in order to correctly use them together.
Just replace your usage of the >> operator with std::getline, so you're using std::getline exclusively, and make sure to check for fail() or eof(). You will find plenty of examples of how to correctly check for end of file and failure conditions, with std::getline, here on stackoverflow.com.

How to print multilple words in c++

I can get the file to save right but I can't seem to get multiple words to write to .txt, like if I type "Hi purple" it just writes "Hi", here is code
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
system("color F0");
string name0;
cout << "Please enter a file name, no spaces/special characters" << endl;
cin >> name0;
name0 = name0+".txt";
system("cls");
cout << " FISHSOFT" << endl;
cout << "The best text editor in the world" << endl << endl;
string text;
cin >> text;
ofstream myfile;
myfile.open (name0.c_str() , ios::out | ios::trunc);
myfile << text;
myfile.close();
system("PAUSE");
return 0;
}
Use std::getline to read an entire line of input including spaces.
cin >> text; will read one whitespace delimited token from the input stream. One word in == one word out.
std::getline(cin, text); will read a whole line. Reading more than that is tricky, but typically a loop around multiple calls to getline.
Suggestion: Save yourself time and fire up your IDE's debugger to see what's happening in your code before posting a question. Almost always faster, and if not, you can make much better, tighter-focused questions.
std::cin is able to get several parameters at once.
That mean you may write:
std::cin >> name0 >> name1 >> name2;
// input: a1 a2 a3
// make: name0: a1, name1: a2, name3:a3
By default, the space is the separator between parameters.
To avoid this behavior, you could use getLine:
std::getline(std::cin, name0);
There are 2 ways to get the string with spaces and special character.
cin.getline(name);
gets(name);
Hope this will serve your purpose.

How to force the user to input in a formatted way in c++

I'm supposed to force the user to input a number then a space then a string and if the format was wrong, I should terminate the program. When I used the cin, the compiler ignored the space and considered the first character of the string to be the one he should check to make sure that the user inputs a space and since the first character is always not a space he terminates.
What should I do ?!
I assume by "when I used the cin" you mean with the >> operator. Reading from an istream with >> is a formatted input function which means the input is pre-formatted for you, one of the effects is skipping over whitespace by default.
There are several ways to solve your problem, including reading a single character at a time (using an unformatted input function such as std::istream::get) or reading a line at a time and parsing the line.
Alternatively, you can turn off skipping of whitespace characters with the noskipws manipulator:
#include <iostream>
#include <string>
int main()
{
int num;
char c;
std::string str;
if (std::cin >> std::noskipws >> num >> c >> str && c == ' ')
std::cout << "ok" << std::endl;
else
std::cout << "Failed" << std::endl;
}
Use std::getline. If you require further help, make sure to post a code sample which demonstrates the problem, otherwise you won't get specific answers.
Example:
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cout << "Please enter a number and a string, separated by a space:";
std::getline(std::cin, input);
// Code to validate input
}

getline not asking for input? [duplicate]

This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 7 years ago.
This is probably a very simple problem but forgive me as I am new.
Here is my code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string name;
int i;
string mystr;
float price = 0;
cout << "Hello World!" << endl;
cout << "What is your name? ";
cin >> name;
cout << "Hello " << name << endl;
cout << "How old are you? ";
cin >> i;
cout << "Wow " << i << endl;
cout << "How much is that jacket? ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << price << endl;
system("pause");
return 0;
}
The problem is that when asked how much is that jacket? getline does not ask the user for input and just inputs the initial value of "0". Why is this?
You have to be careful when mixing operator>> with getline. The problem is, when you use operator>>, the user enters their data, then presses the enter key, which puts a newline character into the input buffer. Since operator>> is whitespace delimited, the newline character is not put into the variable, and it stays in the input buffer. Then, when you call getline, a newline character is the only thing it's looking for. Since that's the first thing in the buffer, it finds what it's looking for right away, and never needs to prompt the user.
Fix:
If you're going to call getline after you use operator>>, call ignore in between, or do something else to get rid of that newline character, perhaps a dummy call to getline.
Another option, and this is along the lines of what Martin was talking about, is to not use operator>> at all, and only use getline, then convert your strings to whatever datatype you need. This has a side effect of making your code more safe and robust. I would first write a function like this:
int getInt(std::istream & is)
{
std::string input;
std::getline(is,input);
// C++11 version
return stoi(input); // throws on failure
// C++98 version
/*
std::istringstream iss(input);
int i;
if (!(iss >> i)) {
// handle error somehow
}
return i;
*/
}
You can create a similar function for floats, doubles and other things. Then when you need in int, instead of this:
cin >> i;
You do this:
i = getInt(cin);
Its because you have a '\n' left lying on the input stream from a previous call.
cin >> i; // This reads the number but the '\n' you hit after the number
// is still on the input.
The easiest way to do interactive user input is to make sure each line is processed independently (as the user will hit enter after each prompt).
As a result always read a line, then process the line (until you get familiar with the streams).
std::string line;
std::getline(std::cin, line);
std::stringstream linestream(line);
// Now processes linestream.
std::string garbage;
lienstream >> i >> garbage; // You may want to check for garbage after the number.
if (!garbage.empty())
{
std::cout << "Error\n";
}
Ignore some characters until line feed is reached.
cin.ignore(256, '\n')
getline (cin,mystr);