cin missing first word of line - c++

I've been having issues in a program involving cin.
My problem is that the first word of everything I input appears to be skipped, possibly because of the way the buffer is handled. I have seen similar posts regarding this but trying to apply their fixes to my code have so far failed. What is supposed to happen is the user inputs a name and that name gets stored in a text file with other entered data. However, it always drops the first word.
#include "string"
#include "stdafx.h"
string _name;
int main()
{
cout << "Choose a name" << endl;
getline(cin, _name);
cout << _name;
ofstream dat;
dat.open("data.txt");
dat << _name;
dat.close();
return 0;
}
This code is where the problem appears to be. I just can't get it to take the first word.

cin >> _name;
This reads the first word on the first line of input into _name.
getline(cin, _name);
This will read the rest of the line into _name. This overwrites the existing contents of name.
Because this overwrites the existing contents of _name, which contains the first word read, this ends up reading all except the first word of the line, as you described.
If you just want to read the entire line into _name, the only thing that needs to be done is to remove the cin >> _name.

If you want to read a name from cin, then your code should look something like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string _name;
cout << "Choose a name : ";
getline(cin, _name);
cout << _name << endl;
// Do something with _name - write to file etc..
// ..
}

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

How to read all of the text on a line starting on that line?

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.

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

.size() string manipulation not reading actual length/size of characters c++

I am trying to read in an essay from a file which I then need to change each beginning letter of a sentence to an upper case letter and then send the corrected essay back to a file called correct.txt. The essay is stored in essay.txt.
So far I am just working with understanding the conversions from files to string in order for me to proceed with the rest of the question. So far, I have a string variable which which holds the essay with the words separated by a single space. I noticed that when I was trying to work with the size of my new string, it was not giving me the correct answer and I cannot figure out why. If you have any suggestions on how I can get it to notice the correct amount of characters, I would really appreciate it.
One more question while you're here, I know that moving forward, in order to change the beginning letters of the sentence to upper case, I need to first find the periods. Once I have this position, I can use pos+2 (including the preceding whitespace after the period) for the character that needs to become upper case. Is this the correct way of going about this and do you have any other tips on how to go forward with this?
Here is my code so far:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
//declaring variables and creating objects
ifstream inputFile;
ofstream outputFile;
char inputFileName[20], outFileName[20];
cout << "Enter name of the file you want to open: " << endl;
cin >> inputFileName;
inputFile.open(inputFileName);
if (inputFile.fail()) {
cout << "Input file opening failed.\n";
exit(1);
}
cout << "Enter name of the file you want to send the output to: " << endl;
cin >> outFileName;
outputFile.open(outFileName);
if (outputFile.fail()) {
cout << "Output file opening failed.\n";
exit(1);
}
//while the file is open, it sends the contents to the string variable "essay"
string essay;
inputFile >> essay;
while (!inputFile.eof()) {
cout << essay << " ";
inputFile >> essay;
}
//this is to check for the correct size of the string "essay" before moving on to the rest of the code
int size = essay.size();
cout << size << endl;
return 0;
}
Your understanding of how the input stream works is incorrect.
The core of your code is this loop:
string essay;
inputFile >> essay;
while (!inputFile.eof()) {
cout << essay << " ";
inputFile >> essay;
}
What this does is that it reads the first word into essay, then, as long as the eof marker is not set on the stream it echoes back the word just read, and then reads another word, overwriting the previous one.
Here's the correct code. Note that checking for eof in a loop condition is a bad idea, because it doesn't quite do what you want, and would also get you stuck in an infinite loop if the stream instead entered an error condition.
string word;
while (inputFile >> word) { // read a word and stop if this fails for any reason
essay += word;
essay += " ";
}
Though I'm not sure why you read the file word by word instead of all at once.
Also, I feel the need to repeat what M.M. said in a comment: your use of raw character arrays on input is unsafe and unnecessary. Just use string. You need to then write inputFile.open(inputFileName.c_str()) unless your standard library is new enough to have the string overloads of these functions, but that is fine. The other way of doing it is dangerous and a very bad habit to get into.
Try include cstring on top of string as well.
String is considered char array which is a more 'unique' way of storing data. You can try the code listed below.
int size = essay.length();

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.