How this program should work:
Enter 4 words:
this is bad
Bad input.
and
Enter 4 words:
hello you love it
Good input.
How I tried it:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
cout << "Enter 4 words:" << endl;
string a, b, c, d;
cin >> a >> b >> c >> d;
}
It reads input after end of the line and I can't figure out how to limit it only to one line. Can you please point me what function I should use? I'll be very grateful for every answer.
Thank you all!
std::getline() should be used when the program's expected input comes from an interactive terminal.
That's what std::getline() does: it reads text until the newline character. operator>> doesn't do that, that's what std::getline() does, and that's what should be used to process a line of typed-in text. Use the right tool, for the right job.
Sadly, many C++ books and tutorials introduce >> too early, before introducing std::getline(), and use it in their examples, simply because it's easier and more convenient to have >> handle the required data type conversion. Unfortunately, this results in a wrong mindset settling in, where >> is thought to be the automatic choice for processing interactive input. It is not.
The correct approach is to use std::getline(). Then, if necessary, construct a std::istringstream, and use that to handle any type conversions from the entered input. Not only does that solve the immediate problem, it also solves the problem of unparsable input putting std::cin into a failed state, with all subsequent attempted input conversions failing as well -- that's another common pitfall.
So, use std::getline(), first:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
int main(void) {
std::cout << "Enter 4 words:" << endl;
std::string line;
std::getline(std::cin, line);
And now, once the line of text is entered, it can be converted to a std::istringstream:
std::istringstream i(line);
Followed by a loop to repeatedly invoke >> in order to count the words in this line. This part you can finish yourself.
P.S. Another common pitfall is using namespace std;. You should not do that, as well. The earlier good programming practices are acquired, the easier the subsequent road on the path towards C++ guru-ism will be.
You should use following command:
std::getline()
This ignore the eventual space as a quote terminating string and you can store the value inside a variable, then see how much words are inside that.
Example:
std::getline (std::cin,name);
Related
I need to create a program that reads in a list of random integers via input redirection and performs various tasks with them. For the purpose of this question I just want to print the sum of each number + 1. Trouble is, I don’t know how to get it to perform the operation on anything but the first number in the list. My mini program (program.cpp) is
#include <iostream>
using namespace std;
int main () {
int input;
bool arb = true;
cin >> input;
while (arb) {
cout << input + 1 << endl;
}
return 0;
}
and a sample textfile (textfile.txt) I'm using contains
9
8
7
6
When I run it it prints out “10” for infinity. What I’d like it do is print out
10
9
8
7
or the equivalent for whatever other text file may be used.
I thought maybe I could somehow reference specific lines in the textfile, but from searching how to do that all the similar questions I could find seemed to have solutions that required fstream, which is something I haven’t learned yet and therefore I’m not allowed to use it (this is for a class assignment).
The only compiler directives I’ve learned are iostream, string, cmath, iomanip, cstdlib, and ctime. The ways to get input I’ve learned are cin >> input, cin.get(input), and cin.getline(input), so if there are other ways of reading in the file besides those 3 that I’m unaware of, unfortunately I can’t use it. Note that my program HAS to use a while loop. The way the program will be run is
./program < whatevertextfile.txt
which I can't change.
given these restrictions, how can I get my program to read in and use each integer in the text file?
The idiomatic way to read a sequence of white-space separated integers in C++ would be
#include <iostream>
using namespace std;
int main () {
int input;
while (cin >> input) {
cout << input + 1 << endl;
}
return 0;
}
Let's come to why this works the way it does.
cin >> input
discards possible white-space and then reads an integer from the standard input. Moreover, it returns a reference of the cin object used. With this returned reference, you can call the bool conversion operator to check if any of the fail bits is set in the given std::basic_ios object. So
while (cin >> input)
does two things. Read an integer from standard input and check if it successfully completed the operation. As long as this operation succeeds, your while loop continues to iterate and you print the numbers.
See http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt for reference on std::basic_istream::operator>>.
See http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool for reference on operator bool.
Edit1: Move references to bottom so that the answer is more readable.
#include <iostream>
#include <string.h>
#include<stdio.h>
using namespace std;
int main()
{
char d,a[9],e[9];
cin.getline(a,9);
cin.getline(e,9);
cin>>d;
puts(a);
puts(e);
cout<<d<<endl;
return 0}
when i enter "hey every one" on the output screen, puts(e) prints a blank line and d prints a random character.second getline function and cinfunction is not working because of first getline. Thanks in advance.
You should read some documentation for the stuff you use:
After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):
- [...]
- count-1 characters have been extracted (in which case setstate(failbit) is executed).
(Emphasize mine)
So the first getline fails if the input is too long and thus leaves std::cin in a bad (i.e. unreadable) state. This makes all successive input operations fail immediately.
Remark: To avoid tons of ugly trouble, you should avoid using C-style strings and the "kind of C-style" member-getline and just use std::string and the non-member std::getline instead.
When you use
cin.getline();
and when you press Enter after entering the string, that enter goes into the next string.
In order to prevent it, use
cin.ignore();
It ignores the Enter and prevents it from entering into another string.
Here is your modified code:
#include<iostream>
#include <cstring>
using namespace std;
int main()
{
char d,a[9],e[9];
cout<<"String:"<<endl;
cin.getline(a,9);
cin.ignore();
cout<<"String:"<<endl;
cin.getline(e,9);
cin>>d;
cout<<a;
cout<<e;
cout<<d<<endl;
return 0;
}
Let's suppose I'd like to read an integer from the console, and I would not like the program to break if it is fed non-integer characters. This is how I would do this:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string input; int n;
cin >> input;
if(!(stringstream(input)>>n)) cout << "Bad input!\n";
else cout << n;
return 0;
}
However, I see that http://www.cplusplus.com/doc/tutorial/basic_io/ uses getline(cin,input) rather than cin >> input. Are there any relevant differences between the two methods?
Also I wonder, since string is supposed not to have any length limits... What would happen if someone passed a 10GB long string to this program? Wouldn't it be safer to store the input in a limited-length char table and use, for example, cin.getline(input,256)?
std::getline gets a line (including spaces) and also reads (but discards) the ending newline. The input operator >> reads a whitespace-delimited "word".
For example, if your input is
123 456 789
Using std::getline will give you the string "123 456 789", but using the input operator >> you will get only "123".
And theoretically there's no limit to std::string, but in reality it's of course limited to the amount of memory it can allocate.
the first gets a line,
the second gets a world.if your input "hello world"
getline(cin,str) : str=="hello world"
cin>>str: str="hello"
and dont worry about out of range, like vector ,string can grow
operator>> reads a word (i.e. up to next whitespace-character)
std::getline() reads a "line" (by default up to next newline, but you can configure the delimiter) and stores the result in a std::string
istream::getline() reads a "line" in a fashion similar to std::getline(), but takes a char-array as its target. (This is the one you'll find as cin.getline())
If you get a 10 GB line passed to your program, then you'll either run out of memory on a 32-bit system, or take a while to parse it, potentially swapping a fair bit of memory to disk on a 64-bit system.
Whether arbitrary line-length size limitations make sense, really boils down to what kind of data your program expects to handle, as well as what kind of error you want to produce when you get too much data. (Presumably it is not acceptable behaviour to simply ignore the rest of the data, so you'll want to either read and perform work on it in parts, or error out)
I just started learning C++. I was just playing around with it and came across a problem which involved taking input of a string word by word, each word separated by a whitespace. What I mean is, suppose I have
name place animal
as the input. I want to read the first word, do some operations on it. Then read the second word, do some operations on that, and then read the next word, so on.
I tried storing the entire string at first with getline like this
#include<iostream>
using namespace std;
int main()
{
string t;
getline(cin,t);
cout << t; //just to confirm the input is read correctly
}
But then how do I perform operation on each word and move on to the next word?
Also, while googling around about C++ I saw at many places, instead of using "using namespace std" people prefer to write "std::"
with everything. Why's that? I think they do the same thing. Then why take the trouble of writing it again and again?
Put the line in a stringstream and extract word by word back:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string t;
getline(cin,t);
istringstream iss(t);
string word;
while(iss >> word) {
/* do stuff with word */
}
}
Of course, you can just skip the getline part and read word by word from cin directly.
And here you can read why is using namespace std considered bad practice.
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
I am new to C++ . I am writing following simple code. I wanted to pass the character[40] into a function and then get the same as output.
If i put a debug at following point.
strcpy_s(x,100,tester);
But it only takes "This" if i write "This is sent at the output". Can anyone please point out what am i missing and whats the reason for only accepting few characters.
// BUSTesting.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "resource.h"
int testFunction(char* tester);
int _tmain()
{
char m[40];
std::cin>>m;
testFunction(m);
}
int testFunction(char* tester)
{
char x[100] ;
memset(x,100,sizeof(x));
strcpy_s(x,100,tester);
std::cout<<x;
return 0;
}
operator>> will stop consuming input at first whitespace character. An alternative would be to use cin.getline() to prevent processing of input due to whitespace.
Note to initialize an array and avoid memset():
char x[100] = "";
Recommend std::string and std::getline() which avoids specifying a maximum number of characters to read from the input stream (avoiding potential buffer overrun problems with fixed sized arrays).
Change this: std::cin >> m; to this cin.getline(m, 39);
cin >> x doesn't get all line characters until end-line when there is a white-space (space, tab, ...) in the input.
Since you are using C++, it is better to use std::string class instead of old C-style strings.
std::cin>>m probably breaks the string on a space for some reason. Break with a debugger and check m's content. If it's only this, you've found the problem.