How to print multilple words in c++ - 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.

Related

there's an extra newline before text ofstream 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';
}
}

String not working with #include <string> and using namespace std

about the code below, string doesn't light up anymore and when I entered "John Smith", only "John" appears, string was working fine for me weeks ago until i tried calling strings function today which didn't work so i tested for a simpler one.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string name;
// Get the user's name
cout << "Please enter your first name: ";
cin >> name;
// Print the greeting
cout << "Hello, " << name << "." << endl;
return 0;
}
string doesn't light up like int
I might be asking at the wrong place but I cant' tell what's the problem, please help :(
To get all the line, use getline(cin, name);
instead of cin >> name;
See http://www.cplusplus.com/reference/string/string/getline/
With std::string's, using std::cin >> someString will only read the first word off the buffer (it will stop at the first whitespace encountered).
Use getline(std::cin, someString) instead to read the entire line.
std::cin gets only characters to first 'white' character, like space, tab or enter.
If you want to read whole line use e.g. getline()
string line;
cin.clear(); //to make sure we have no pending characters in input buffer
getline(cin, line);

Writing to a file in C++

I'm trying to make a program that will get the user input of a new file name, create the file, and write to it. It works but it will only write the first word of the string to the file. How can i get it to write the full string? thanks.
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (;;)
{
char *myFile = " ";
string f = " ";
string w = " ";
cout <<"What is the name of the file you would like to write to? " <<endl;
cin >>f;
ofstream myStream(f,ios_base::ate|ios_base::out);
cout <<"What would you like to write to " <<f <<" ? ";
cin >>w;
myStream <<w;
if (myStream.bad())
{
myStream <<"A serious error has occured.";
myStream.close();
break;
}
}
}
According to this post, you should consult this reference to use a method like getline().
Also, when you are writing out I recommend that you flush the output (cout.flush()) before ending the program, especially in this case, since I presume you are ending the program with a ctrl-C break.
In formulating a suggestion, I will read data into char*, and convert them to "string" in case you will use them elsewhere in your program.
I tested this code in MS Visual C++ Express.
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (;;)
{
char *myFile = new char[200]; // modified this line
//added this line
char *myInput = new char[200];
string f = " ";
string w = " ";
cout << "What is the name of the file you would like to write to? " << endl;
cin.getline(myFile, 200);//modified this line
f = (myFile);//added this line
cin.clear(); //added this line
ofstream myStream(f, ios_base::ate | ios_base::out);
cout << "What would you like to write to " << f << " ? ";
cin.getline(myInput, 200);//edited this line
w = string(myInput);//added this line
myStream << w;
myStream.flush();//added this line
if (myStream.bad())
{
myStream << "A serious error has occured.";
myStream.close();
break;
}
delete myFile;
delete myInput;
}
}
You have to use std::getline() to read the entire line:
std::getline(std::cin >> std::ws, w);
The >> std::ws part gets rid of leading whitespace which is needed because the newline left in the stream from the previous extraction will prevent std::getline() from fully consuming the input.
When inserting data into the stream you need to make sure it gets flushed (because, as the other answer said, you're probably using Ctrl+C to terminate the program and you may not see output during the program run). You can use the std::flush manipulator to flush the output:
myStream << w << std::flush;
cin<<w; cin would stop consuming input character when it encounter whitespace tab and other unseeable characters.
you should probably use std::getline() instead.
take a look at this page for ref.
http://en.cppreference.com/w/cpp/string/basic_string/getline
Or you can use manipulator to not skip whitespace.

Write different user imput data in the same line on a txt file in C

I want to write a simple program which collects data from user input to save into a txt file.
I've find several ways to collect and save the data but I couldn't find a way to write different instances from user input into the same line on the txt file.
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
char book[30];
char author[30];
char quote[64];
ofstream myfile;
myfile.open ("myfile.txt", ios::in | ios::ate);
if (myfile.is_open())
{
cout << "Enter the name of the Book: ";
fgets(book, 30, stdin);
cout << "Enter the name of the Author: ";
fgets(author, 30, stdin);
cout << "Type the quote: ";
fgets(quote, 64, stdin);
myfile << ("%s;",book) << ("%s;",author) << ("%s;",quote);
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
The out put on the file is:
Book01
Author01
"This is the quote!"
I'd like to be in the same line:
Book01; Author01; "This is the quote!"
Thanks for you help and attention!
The fgets function includes the newline character in the buffer, so when you write them those newlines will appear in myfile. You could simply remove the newlines with something like this:
book[strlen(book)-1] = '\0';
But mixing fgets with cout is a bit odd to begin with, so just get rid of it and use cin instead. For example:
cin >> book;
From the fgets doc: http://www.cplusplus.com/reference/cstdio/fgets/
A newline character makes fgets stop reading, but it is considered a
valid character by the function and included in the string copied to
str.
So, at the end of the data readed, there is a \n

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);