How to get cin multiple times in different lines? - c++

I want to get input twice with one variable a string and the other character, but it always comes out compilation error, how do I solve this problem. I've tried cin.clear(); but it seems not working in this case.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <string>
using std::string;
using std::getline;
int main(){
string name;
cout << "Please input a string." << endl;
getline (cin, name);
cout << "Hello, there, "<< name <<".\n";
char ccc;
cout << "Please input a character." << endl;
getline (cin, ccc);
cout << "This is a alphabet:" << ccc << endl;
return 0;
}
I expect the output will be like:
Please input a string.
John
Hello, there, John.
Please input a character.
c
This is a alphabet:c

I have used cin.ignore(); before. It should clear the buffer. Also char should use getchar instead of getline.

There is no version of getline() which accepts a char as its second argument. Instead, you probably want the version which accepts a char*. You will need to modify your code to read a string that contains one character.

Try getchar() instead of getline() on the second one.

Related

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

**Compiler error** - getline() function not accepting first parameter "std:ifstream" what is my issue?

I'm writing a program for my homework that counts words and lines. I'm wondering why i get the error: "no instance of overloaded function "getline" matches the argument list. Argument types are (std::ifstream, int)"
I was certain "infile" was of std::ifstream argument type. Could the problem be visual studio or am i quick to blame something without prior knowledge?
P.S i searched a bit but would not find a thread with exactly the same problem.. there are similar ones but they end up being that someone put a string of the file name and not the stream itself. Also keep in mind i'm in the middle of writing this i didn't finish yet.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream infile;
infile.open("Lear.txt");
string word;
int countWords = 0, countLines = 0;
while (!infile.eof())
{
infile >> word;
countWords++;
getline(infile, countLines); //issue area here at infile
countLines++;
}
cout << "Words: " << setw(9) << countWords << endl;
cout << "Lines: " << setw(9) << countLines << endl;
infile.close();
}
There is no std::getline overload that takes an int second parameter. I assume you meant to pass your std::string variable instead.
getline(infile, word);
You should remove the infile >> word; line or decide whether you want to use it or std::getline. I don't think you want both in this case.
This will fix the compiler error but not your program logic. If you use std::getline you'll have to parse each line to count words.

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.

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.

Mixed data typeinput in C++

Why does this program run fine?
#include<iostream>
using namespace std;
int main()
{
cout <<"What year was your house built?\n";
int year;
cin >> year;
cout << "What is its street address?\n";
char address[80];
cin>>address;
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
return 0;
}
And why does this program not give the chance to enter the address?
#include <iostream>
int main()
{
using namespace std;
cout <<"What year was your house built?\n";
int year;
cin >> year;
cout << "What is its street address?\n";
char address[80];
cin.getline(address, 80);
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
return 0;
}
cin>> leaves the newline character (\n) in the iostream. If getline is used after cin>>, the getline sees this newline character as leading whitespace, thinks it is finished and stops reading any further.
Two ways to solve the problem:
Avoid putting getline after cin >>
OR
Consume the trailing newline character from the cin>> before calling getline, by "grabbing" it and putting it into a "dummy" variable.
string dummy;
getline(cin, dummy);
Why does the first program work & Second doesn't?
First Program:
The cin statement uses the entered year and leaves the \n in the stream as garbage. The cin statement does NOT read (or "grab") \n. The cin ignores \n when reading data. So cin in program 1 can read the data properly.
Second Program:
The getline, reads and grabs \n. So, when it sees the \n left out from cin, it grabs the \n and thinks it is finished reading, resulting in second program not working as you expected.
Sit down for a second. This is not easy to explain properly.
When your program gets to a point where it reads from std::cin, it does not just automatically wait for you to type something. std::cin is an input stream, the same as you use to read from a file on disk. The only reason it waits is if there is not enough data available yet to satisfy the read request.
Meanwhile, when you run your program from the console, the console window itself is also a program. It is interpreting your key presses and translating them into text, and feeding that text a line at a time to the standard input of your program (so that std::cin can see it). This is important and useful, because it allows the backspace key to work the way you expect it to.
So if your program is supposed to read a number, and you type a number, your program will not see the number until you hit return to complete the line. However, the newline character is still sitting in the input stream, because you didn't read it yet. The operator>> skips whitespace before the value that it's trying to read, but it leaves behind any whitespace after the value.
Now, if the next reading operation is another call to operator>>, then it does the same thing again and it works fine: the newline that we didn't read before is whitespace, so it gets skipped, and then the next thing gets read.
However, the getline() function reads from the current point until the next newline. It never skips any leading or trailing whitespace, and an empty line is considered completely valid. So if you typed a number and hit return, then the getline() call will see the newline and finish reading right away, because it already has an end of the line. The program does not stop because there was already enough data available to finish the operation.
To fix this, the safest, simplest and most robust way of dealing with the input is to always read the entire line first, and then re-interpret the contents of the line. To make this easier, we will use the std::string class to represent strings. We can read into the string instance with std::getline (notice: a global function, not a member function of cin), and create a std::stringstream instance from that string.
The idea is: the program will always wait at an input request, because the previous request always read the newline character (because we read the entire line). So that makes the control flow work the way we expected it to. The std::stringstream instance can be treated like a file or standard input: it's just another stream, except it takes its data from the string. So we can get numbers out of it with operator>>, and so on.
The other benefit of this comes when the user inputs invalid data. It can be quite hard to recover from this properly, if you are just reading directly from std::cin. But if you are using the stringstream as a "buffer", then you can just throw it away and try again with a new line of input.
An example:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
using namespace std;
string line;
int year;
while (true) {
cout << "What year was your house built?" << endl;
getline(cin, line);
stringstream input(line);
if (line >> year) { break; }
}
cout << "What is its street address?\n";
getline(cin, line);
cout << "Year built: " << year << endl;
cout << "Address: " << line << endl;
cout << "Done!\n";
}
Maybe you have a stray terminator in cin?|
Try cin.clear();